Search code examples
javascriptphpmysqlajaxcroppie

Retrieving the image using PHP


I am beginner in PHP and Ajax query. I am trying to upload an profile image using croppie.js plugin. When I am uploading the image, the image would be saved like 1580192100.png. But my problem is there is an impossible to retrieve the image according to the userid.

Here is the code which I tried. profilepic.php page

<?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);



?>

The php fetch code would be;

<?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

I don't know where I went t wrong. Please help me.


Solution

  • It looks like the update statement sets the image name in the database rather than any base64 encoded data ( better to save just the name otherwise the table will become huge ) so when you try to display the image you need to read the image data. I modified the above to use a 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();
            }
        }
    ?>