You can write STDOUT directly to a file in PHP, which is much simpler and simpler than using output buffering.
Do this at 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');
Why at the very beginning you can ask? No file descriptors need to be opened, 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.
In my example here, I redirected standard input to / dev / null and the descriptors of the output file and the error file to the log files. This is common practice when creating a daemon script in PHP.
To write the application.log file, this will be enough:
echo "Hello world\n";
To write to error.log , you would need:
fwrite($STDERR, "Something went wrong\n");
Note that when changing input, output, and error descriptors, the built-in PHP constants STDIN, STDOUT, and STDERR will not be available. PHP will not update these constants for new descriptors, and they are not allowed to override these constants (they are called constants for some reason).
Bas Peters Sep 29 '10 at 15:17 2010-09-29 15:17
source share