Php – Pulling IMG Into PHP File


I have a PHP file and an image in the same directory. How could I get the PHP file to set it's headers as jpeg and "pull" the image into it. So if I went to file.php it would show the image. If I rewrite file.php to file_created.jpg and it needs to work.

Best Solution

Rather than use file_get_contents as suggested by another answer, use readfile and output out some more HTTP headers to play nicely:

    $filepath= '/home/foobar/bar.gif'
    header('Content-Type: image/gif');
    header('Content-Length: ' . filesize($filepath));

readfile reads the data from the file and writes direct to the output buffer, whereas file_get_contents would first pull the entire file into memory and then output it. Using readfile makes a big difference if the file is very large.

If you wanted to get cuter, you could output the last modified time, and check the incoming http headers for the If-Modified-Since header, and return an empty 304 response to tell the browser they already have the current's a fuller example showing how you might do that:

$filepath= '/home/foobar/bar.gif'


$headers = apache_request_headers(); 
if (isset($headers['If-Modified-Since']) && 
    (strtotime($headers['If-Modified-Since']) >= $mtime)) 
    // Client's cache IS current, so we just respond '304 Not Modified'.
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT', true, 304);

header('Content-Length: '.filesize($filepath));
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT');