从PHP中的文件系统获取图像

kew*_*tek 0 php file-io image

我正在编写一个PHP程序,它将从文件系统中获取图像并将其显示在返回的页面上.问题是该文件未存储在/ var/www目录中.它存储在/ var/site/images中.我怎样才能做到这一点?我是否必须用fopen将其读入内存,然后回显内容?

Cod*_*lan 5

用于fpassthru将文件系统中的内容转储到输出流.事实上,文档fpassthru包含了一个关于你正在尝试做什么的演示:http://us3.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;

?>
Run Code Online (Sandbox Code Playgroud)

  • 您需要通过`img`标签引用上面的PHP脚本:`<img rel="nofollow noreferrer" src ="image.php?path =/var/www/foo.png"/>` - 这会引发安全问题,但从逻辑上讲,这就是你想要做的.所以`image.php`脚本实际上是独立的,你可以给它一个查询参数,告诉它要呈现什么样的图像.但是你应该做很多输入清理来检查文件是否有效等. (2认同)