Получение изображения с помощью PHP - PullRequest
0 голосов
/ 28 января 2020

Я новичок в PHP и Ajax query. Я пытаюсь загрузить profile image, используя croppie.js plugin. Когда я загружаю image, изображение будет сохранено как 1580192100.png. Но моя проблема в том, что retrieve the image невозможно в соответствии с userid.

Вот код, который я пробовал. profilepic.php страница

<?php

session_start();
require_once "../auth/dbconnection.php";

if (isset($_POST['image'])) {

    $croped_image = $_POST['image'];
    list($type, $croped_image) = explode(';', $croped_image);
    list(, $croped_image)      = explode(',', $croped_image);
    $croped_image = base64_decode($croped_image);
    $image_name = time().'.png';


 // Valid file extensions
 $allowTypes = array( 'bmp', 'jpg', 'png', 'jpeg' , 'JPG');

// if(in_array($fileType, $allowTypes)){

    $stmt = $conn->prepare("UPDATE users SET image = ? WHERE user_id= ?");
    $stmt->bind_param("si", $image_name, $_SESSION['user_id']);
    $stmt->execute();
    if($stmt->affected_rows === 0);


      file_put_contents('blog/'.$image_name, $croped_image);
    echo 'Cropped image uploaded successfully.';




    }else{

        echo "ERROR: Could not prepare query: $stmt. " . mysqli_error($conn);

    }

    $stmt->close();
//    mysqli_stmt_close($stmt);



?>

Код php fetch будет:

<?php

require_once 'auth/dbconnection.php';
$sql="SELECT image FROM users WHERE user_id= '".$_SESSION['user_id']."'";
        if($result = mysqli_query($conn, $sql)){
        if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){

$out= '<img src="data:image/png;base64,'.base64_encode($row['image']).'" alt="">';
echo $out;

        }
    }
}
?>

enter image description here

Я не знаю где я ошибся. Пожалуйста, помогите мне.

1 Ответ

1 голос
/ 28 января 2020

Похоже, что оператор update устанавливает имя изображения в базе данных, а не любые данные в кодировке base64 (лучше сохранить только имя, иначе таблица станет огромной), поэтому при попытке отобразить изображение, которое необходимо прочитать данные изображения. Я изменил выше, чтобы использовать prepared statement

<?php
    if( !empty( $_SESSION['user_id'] ) ){

        require_once 'auth/dbconnection.php';


        $sql='select `image` from `users` where `user_id`=?';
        $stmt=$conn->prepare( $sql );
        $stmt->bind_param( 's',$_SESSION['user_id'] );

        # determine the correct path for the image
        $filepath=$_SERVER['DOCUMENT_ROOT'] . '/profile/blog/';

        $res=$stmt->execute();
        if( $res ){
            $stmt->store_result();
            $stmt->bind_result($filename);

            while( $stmt->fetch() ){
                /* 
                    You store the filename ( possibly path too ) 
                    so you need to read the file to find it's
                    raw data which you will use as image source.
                    Use the filepath to find the image!!
                */
                printf(
                    '<img src="data:image/png;base64, %s" alt="" />',
                    base64_encode( file_get_contents( $filepath . $filename ) )
                );      
            }
            $stmt->free_result();
            $stmt->close();
            $conn->close();
        }
    }
?>
...