使用 PHP 检索图像

Retrieving the image using PHP

我是 PHPAjax query 的初学者。我正在尝试使用 croppie.js plugin 上传 profile image。当我上传 image 时,图像将被保存为 1580192100.png。但是我的问题是根据userid不可能retrieve the image

这是我试过的代码。 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;

        }
    }
}
?>

我不知道我哪里做错了。请帮助我。

看起来 update 语句在数据库中设置图像名称而不是任何 base64 编码数据(最好只保存名称,否则 table 会变得很大)所以当你尝试要显示图像,您需要读取图像数据。我修改了上面的内容以使用 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();
        }
    }
?>