Sarita
Sarita

Reputation: 1

Displaying an image from a database

I have looked at most of the threads re this topic but I am still in the dark! I understand that storing an image in a database is not best practice but that's what I have. I have managed to upload the images no problem but when I try to display them I get this message.

The image * cannot be displayed because it contains errors.

I have tested the code to see if the file is actually been selected by echoing the file content and I get the pages of code relating to the image but when I try to display the image using the header (Content-type:image/jpeg) I get the above message. I am storing the image as a longblob. This is my code

<?php
$username = "root";
$password = "";
$host = "localhost";
$database = "test";

mysql_connect($host, $username, $password)
    or die("Can not connect to database:   ".mysql_error());

mysql_select_db($database) or die("Can not select the database: ".mysql_error());

$id = 3;

if (!isset($id) || empty($id) || !is_int($id)) {
    die("Please select your image!");
} else {
    $query = mysql_query("SELECT image FROM images WHERE image_id='".$id."'")
        or die(mysql_error());
    //echo $query;
    $row = mysql_fetch_row($query);
    $content = $row['image'];

    header('Content-type: image/jpg');
    echo $content;
}    

Any help much appreciated Thanks# Sarita

Upvotes: 0

Views: 219

Answers (2)

Oswald
Oswald

Reputation: 31637

  1. <?php is missing. This leads to your code not being interpreted as PHP, but send to the client unprocessed.
  2. Remove ?>. It can lead to extra output that you did not intended. Extra output that you did not intended might be acceptable in text file, but can trip the parser of binary files.
  3. Open an image that cannot be displayed because it contains errors with a text editor to see additional errors.

Upvotes: 1

Adder
Adder

Reputation: 5868

The mime type should be image/jpeg not image/jpg.

Make sure there is nothing before <?php and nothing after ?> at the end, including the unicode BOM (which some editors might not display).

If gpc_magic_quotes is on, you might have stored the image in the database with additional backslashes in it. Make sure the images in the database are formatted correctly.

Upvotes: 0

Related Questions