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.
-
Should be easy as:
<?php $filepath= '/home/foobar/bar.jpg'; header('Content-Type: image/jpeg'); echo file_get_contents($filepath); ?>You will just have to figure out how to determine the correct mime type, which should be pretty trivial.
Crescent Fresh : "readfile($filepath);" is even shorter -
Rather than use file_get_contents as suggested by another answer, use readfile and output out some more HTTP headers to play nicely:
<?php $filepath= '/home/foobar/bar.gif' header('Content-Type: image/gif'); header('Content-Length: ' . filesize($filepath)); readfile($file); ?>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 version....here's a fuller example showing how you might do that:
$filepath= '/home/foobar/bar.gif' $mtime=filemtime($filepath); $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); exit; } header('Content-Type:image/gif'); header('Content-Length: '.filesize($filepath)); header('Last-Modified: '.gmdate('D, d M Y H:i:s', $mtime).' GMT'); readfile($filepath);
0 comments:
Post a Comment