Search code examples
phpimagedownloadserverwampserver

why downloaded image is damaged?


I want to get binary data of image with jpg format from database and make download link for it with below code.
It work on wamp server and when download is completed it is opened and file isn't damaged and it shows that file is stored correctly in database, but doesn't work on real server and download link is made but when download is completed file doesn't open.
I try it for pdf files and it work both on server and wampserver.
In below code $row is fill correctly and I'm sure that database value doesn't have problem.
$content is binary value of image.
Does server need specific setting?

    $sql = "SELECT * FROM files WHERE  file_id= ? ";
    $params = array((int)$_POST["btn_save_file"]);
    $table = sqlsrv_query( $conn, $sql, $params);
    $row = sqlsrv_fetch_array( $table, SQLSRV_FETCH_ASSOC);
    $message=sqlsrv_errors();
    $content =$row["file_data"];
    $temp = tmpfile();
    fwrite($temp,$content);
    $name="img".rand(1,1000).".jpg";
    $a=fstat ($temp);
    header('Content-type: image/jpg');
    header('Content-Length: '.$a["size"]);
    header("Content-Disposition: attachment; filename=".$name);
    echo $content;
    fclose($temp);

Solution

  • The answer that Charlotte Dunois sent in comments is my solution (disabling output buffering).
    I used "ob_end_clean()" before making download link, and it worked.