如何将STDOUT重定向到PHP中的文件?

如何将STDOUT重定向到PHP中的文件?

问题描述:

下面的代码几乎可以用,但这并不是我真正的意思:

The code below almost works, but it's not what I really meant:

ob_start();
echo 'xxx';
$contents = ob_get_contents();
ob_end_clean();
file_put_contents($file,$contents);

有更自然的方法吗?

可以将STDOUT直接写到PHP中的文件中,这比使用输出缓冲更加容易和直接.

It is possible to write STDOUT directly to a file in PHP, which is much easier and more straightforward than using output bufferering.

在脚本的最开始处执行此操作:

Do this in the very beginning of your script:

fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
$STDIN = fopen('/dev/null', 'r');
$STDOUT = fopen('application.log', 'wb');
$STDERR = fopen('error.log', 'wb');

为什么一开始您可能会问?尚未打开任何文件描述符,因为当您关闭标准输入,输出和错误文件描述符时,前三个新描述符将成为NEW标准输入,输出和错误文件描述符.

Why at the very beginning you may ask? No file descriptors should be opened yet, because when you close the standard input, output and error file descriptors, the first three new descriptors will become the NEW standard input, output and error file descriptors.

在这里的示例中,我将标准输入重定向到/dev/null,并将输出和错误文件描述符重定向到日志文件.在PHP中创建守护程序脚本时,这是常见的做法.

In my example here I redirected standard input to /dev/null and the output and error file descriptors to log files. This is common practice when making a daemon script in PHP.

要写入 application.log 文件,就足够了:

To write to the application.log file, this would suffice:

echo "Hello world\n";

要写入 error.log ,必须要做的事情:

To write to the error.log, one would have to do:

fwrite($STDERR, "Something went wrong\n"); 

请注意,当您更改输入,输出和错误描述符时,内置的PHP常量STDIN,STDOUT和STDERR将变得不可用. PHP不会将这些常量更新为新的描述符,也不允许重新定义这些常量(毕竟,它们被称为常量是有原因的).

Please note that when you change the input, output and error descriptors, the build-in PHP constants STDIN, STDOUT and STDERR will be rendered unusable. PHP will not update these constants to the new descriptors and it is not allowed to redefine these constants (they are called constants for a reason after all).