7

I'm trying to load an image through PHP, but I don't know how. The filename is stored in the database, such as image.jpg

if($_GET['image']){
    // Client requesting image, so retrieve it from DB
    $id = mysql_real_escape_string($_GET['image']);
    $sql = "SELECT * FROM $tbl_name WHERE id = '$id' LIMIT 1";
}

The client needs to request an image like so

http://example.com/index.php?image=1

And then it should return the image, so it can be embedded like this:

<img src="http://example.com/index.php?image=1" alt="" />

Is this possible?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Adam
  • 1,957
  • 3
  • 27
  • 56

3 Answers3

23
$img = 'path/to/image.jpg';
header('Content-Type: image/jpeg');
readfile($img);

just tested it

joschua011
  • 4,157
  • 4
  • 20
  • 25
2

You can use the GD library for that. You start by creating a resource using a function like http://php.net/imagecreatefromjpeg. You will need to provide the path as a parameter.

After that, you just output the resource using a function like http://php.net/imagejpeg.

Don't forget to send the content type header, and also to use imagedestroy on the resource.

Update:

Consider this sample:

$im = imagecreatefromjpeg('path/to/image.jpg');
header('Content-Type: image/jpeg');
imagejpeg($img);
imagedestroy($img);
dda
  • 6,030
  • 2
  • 25
  • 34
mishu
  • 5,347
  • 1
  • 21
  • 39
  • @safarov maybe it would make it easier to extend if certain modifications are needed.. I did not say it is the only way, I just suggested an option.. – mishu Mar 31 '12 at 20:00
0

I suggest you first make a file called image.php. So you will call image.php?id=1

Have image.php header be the image type. header('Content-Type: image/jpeg');

Then you can use the GDImage library in PHP to load the image, and output it. Or you can read the file and output it. The header() is key.

David
  • 4,313
  • 1
  • 21
  • 29