简体   繁体   English

NGINX / PHP - 无法通过php脚本提供jpeg

[英]NGINX/PHP - Cannot serve jpeg via php script

The following script is trivial and works ok apache without issue 以下脚本是微不足道的,并且没有问题就可以正常运行apache

header('Content-Type: image/jpeg');
echo file_get_contents('./photo.jpg');

On NGINX/PHP-FPM I get a blank page. 在NGINX / PHP-FPM上,我得到一个空白页面。 I have tried two different virtual servers. 我尝试了两种不同的虚拟服务器。 One I created, and the homestead improved box ( https://github.com/Swader/homestead_improved ) which is based on Laravel Homestead. 一个我创建的,宅基地改进了盒子( https://github.com/Swader/homestead_improved ),它基于Laravel Homestead。

Error reporting is on, there are no errors. 错误报告已启用,没有错误。 If I remove the header and just use: 如果我删除标题,只需使用:

echo file_get_contents('./photo.jpg');

I get the binary converted to ASCII and see the strange characters; 我把二进制转换为ASCII并看到奇怪的字符; the file is being loaded correctly. 正确加载文件。

I thought the issue might be a missing header, so I tried content length: 我认为问题可能是缺少标题,所以我尝试了内容长度:

header('Content-Type: image/jpeg');
$contents =  file_get_contents('./photo.jpg');

header('Content-length: ' . strlen($contents));
echo $contents;

This gives a different result: The page never loads, as if the browser never receives all the bytes it's expecting. 这会产生不同的结果:页面永远不会加载,就像浏览器永远不会收到它所期望的所有字节一样。

If I print strlen($contents) it displays the file size in bytes. 如果我打印strlen($contents)它会以字节为单位显示文件大小。 PHP is loading the image correctly, but it's never reaching the browser. PHP正在正确加载图像,但它永远不会到达浏览器。

The script works on an Apache server so the issue seems to be NGINX or PHP-FPM. 该脚本适用于Apache服务器,因此问题似乎是NGINX或PHP-FPM。

I have tried different images (one 80kb, one 2.2mb), the result is the same. 我尝试过不同的图像(一个80kb,一个2.2mb),结果是一样的。 I've also tried readfile instead of file_get_contents . 我也尝试过readfile而不是file_get_contents

Update 更新

In Chrome developer tools, the full image is downloaded and shown in the Network tab. 在Chrome开发者工具中,会下载完整图像并显示在“网络”标签中。 The browser is getting the data but it's not displayed. 浏览器正在获取数据,但不会显示。

Your problem lies in process memory. 你的问题在于进程内存。 PHP uses a different configuration file when running under PHP-FPM then when running under Apache for instance. PHP在PHP-FPM下运行时使用不同的配置文件,然后在Apache下运行时使用。

The problem with file_get_contents is that it reads the entire file into memory. file_get_contents的问题在于它将整个文件读入内存。 In the case of an image file, memory reaches its limit and the http response never completes. 对于映像文件,内存达到其限制,http响应永远不会完成。

To fix the problem, you can either stream the image using fopen or increase PHP-FPM php's memory limit. 要解决此问题,您可以使用fopen流式传输图像或增加PHP-FPM php的内存限制。

Like Scriptonomy said the memory can be an issue. 就像Scriptonomy所说,记忆可能是一个问题。 You can also use readfile 您也可以使用readfile

https://secure.php.net/manual/en/function.readfile.php https://secure.php.net/manual/en/function.readfile.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM