PHP exec() обрезает вывод stdout/output

Категория: PHP

Ф-ция PHP exec() обрезает вывод output (результат выполнения stdout).

В моем случае нужно было получить JSON от внешней программы:

$lastLine = exec('/path/my_command.sh', $outputLines, $exitCode);

В результате переменные $lastLine и $outputLines содержали обрезанную JSON строку.

Причина была в том, что stdout вывод не помещается в установленный лимит в опции output_buffering:

cat /etc/php/7.4/cli/php.ini | grep output_buffering
output_buffering = 4096

Решение

Увеличить output_buffering или писать вывод в файл:

exec('/path/my_command.sh > /tmp/output.json', null, $exitCode);
$json = file_get_contents('/tmp/output.json');
// unlink('/tmp/output.json');

Документация output_buffering из php.ini:

; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
;   functions.
; Possible Values:
;   On = Enabled and buffer is unlimited. (Use with caution)
;   Off = Disabled
;   Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096

; Transparent output compression using the zlib library
; Valid values for this option are 'off', 'on', or a specific buffer size
; to be used for compression (default is 4KB)
; Note: Resulting chunk size may vary due to nature of compression. PHP
;   outputs chunks that are few hundreds bytes each as a result of
;   compression. If you prefer a larger chunk size for better
;   performance, enable output_buffering in addition.
; Note: You need to use zlib.output_handler instead of the standard
;   output_handler, or otherwise the output will be corrupted.
; http://php.net/zlib.output-compression
zlib.output_compression = Off

#php, #php exec(), #stdout, #php exec stdout output length cut short

категория: PHP