Hey all,

I am trying to figure out how to enable images to be saved as an image file when i display them in php. Right now when i right click on the image, it says save image as.. but then it wont save it as anything other than the php code itself. Any ideas?


/*** some basic sanity checks ***/
if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
    /*** assign the image id ***/
    $image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
    try     {
        /*** connect to the database ***/
        $dbh = new PDO("mysql:host=localhost;dbname=informationdb", 'root', '');

        /*** set the PDO error mode to exception ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        /*** The sql statement ***/
        $sql = "SELECT image, image_type FROM testblob WHERE image_id=$image_id";

        /*** prepare the sql ***/
        $stmt = $dbh->prepare($sql);

        /*** exceute the query ***/

        /*** set the fetch mode to associative array ***/

        /*** set the header for the image ***/
        $array = $stmt->fetch();

        /*** check we have a single image and type ***/
        if(sizeof($array) == 2)
            /*** set the headers and display the image ***/
            header("Content-type: ".$array['image_type']);

            /*** output the image ***/
            echo $array['image'];
            throw new Exception("Out of bounds Error");
    catch(PDOException $e)
        echo $e->getMessage();
    catch(Exception $e)
        echo $e->getMessage();
        echo 'Please use a real id number';
6 Years
Discussion Span
Last Post by qazplm114477

I'm guessing you are saving the image as a blob in the database and outputting it with image headers()?

Personally I haven't done this before but here's my 2 cents.

$url= 'imageFile.php';
$img = 'your/desired/folder/image.jpg';
//note: allow_url_fopen has to be true if you are entering a url
file_put_contents($img, file_get_contents($url));

//serve the image
$file = $img;
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));

my suggestion is to save the file somewhere temporarily and then send it as a jpg/png/gif

see http://php.net/manual/en/function.readfile.php

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.