How to display images on browser using php from a database

Discussion in 'PHP' started by vijaybhaskar184, Feb 16, 2009.

  1. #1
    Hi,
    how to retrieve images stored in database using php and then display it on browser.
     
    vijaybhaskar184, Feb 16, 2009 IP
  2. Altari

    Altari Peon

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I'm sure someone can offer a much cleaner way of doing this, but this is how I've done it thus far.

    On the page that displays the image, you'll need to initiate some query/code to specify the image. You could use the image ID from the database, the user ID if it's an avatar, etc. In any event, place this as a $_GET variable in the image source.
    <img src="http://www.mysite.com/images.php?id=<?php echo($imageID); ?>" />
    PHP:
    On the page that calls the image, image.php from above, you'll need to write the header as the correct MIME type, which should be stored in the database along with the binary of the image.
    $imageID = $_GET['id'];
    
    // Get the image from the database
    $result = mysql_query("SELECT * FROM my_image_table WHERE imageID = $imageID;") or die(mysql_error());
    $image = mysql_fetch_array($result);
    
    // assign some variables to make it prettier to read
    $name = $image['imageName'];
    $mime = $image['imageMime'];
    $data = $image['imageData'];
    $size = $image['imageSize'];
    
    // tell the browser what kind of file we're dealing with
    header("Content-type: $mime");
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Length: $size");
    
    // output the image
    print $data;
    
    PHP:
    This page should (with some tweaking because I'm sure I made some errors) render an image so it can be accurately displayed on the calling page.
     
    Altari, Feb 16, 2009 IP
  3. vijaybhaskar184

    vijaybhaskar184 Member

    Messages:
    98
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #3
    Here imageName,imageMime,imageData,imageSize are 4 columns in the table right,
    Actually i tried to dispaly imageData directly and it did not work.
     
    vijaybhaskar184, Feb 17, 2009 IP
  4. Altari

    Altari Peon

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yes, they are four separate columns. Your image table should have (at least) : id, name, mime, size, data.

    If you display the imageData directly, the page will just echo the image's code (same thing if you opened up and image with Notepad). You need to create a separate page that will send the image headers (mime, name and size).
     
    Altari, Feb 17, 2009 IP