简体   繁体   中英

NGINX/PHP - Cannot serve jpeg via php script

The following script is trivial and works ok apache without issue

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

On NGINX/PHP-FPM I get a blank page. 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.

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; 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. PHP is loading the image correctly, but it's never reaching the browser.

The script works on an Apache server so the issue seems to be NGINX or PHP-FPM.

I have tried different images (one 80kb, one 2.2mb), the result is the same. I've also tried readfile instead of file_get_contents .

Update

In Chrome developer tools, the full image is downloaded and shown in the Network tab. 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.

The problem with file_get_contents is that it reads the entire file into memory. In the case of an image file, memory reaches its limit and the http response never completes.

To fix the problem, you can either stream the image using fopen or increase PHP-FPM php's memory limit.

Like Scriptonomy said the memory can be an issue. You can also use readfile

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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