Reputation: 61
I'm writing a PHP program that will get an image from the filesystem and display it on the returned page. The catch is that the file isn't stored in the /var/www directory. It's stored in /var/site/images. How can I do this? Do I have to read it into memory with fopen, then echo the contents?
Upvotes: 0
Views: 3107
Reputation: 32748
Use fpassthru
to dump the contents from the file system to the output stream. In fact the docs for fpassthru
contains a demo of exactly what you're trying to do: https://www.php.net/fpassthru
<?php
// open the file in a binary mode
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// send the right headers
// - adjust Content-Type as needed (read last 4 chars of file name)
// -- image/jpeg - jpg
// -- image/png - png
// -- etc.
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
fpassthru($fp);
fclose($fp);
exit;
?>
Upvotes: 5