15

I'm running the PHP CLI through a NSTask in MacOS, but this question is more about the CLI itself.

I'm listening to the stderr pipe, but nothing is output there no matter what file I try to run:

  • If the file type is not a plain text, stdout sets to ?.
  • If the file is a php script with errors, the error messages are still printed to stdout.

Is there a switch to the interpreter to handle errors through stderr? Do I have an option to detect errors other than parsing stdout?

hakre
  • 178,314
  • 47
  • 389
  • 754
Petruza
  • 10,275
  • 24
  • 74
  • 121

4 Answers4

20

The display_errors directive (can be set everywhere) takes optionally the parameter "stderr" for it to report errors to stderr instead of stdout or completely disabled error output. Quoting from the PHP manual entry:

Value "stderr" sends the errors to stderr instead of stdout. The value is available as of PHP 5.2.4.

Alternatively if you're using the commandline interface and you want to output the errors your own you can re-use the command-line nput/output streams:

fwrite(STDERR, 'error message');

Here STDERR is an already opened stream to stderr.

Alternatively if you want to do it just for this script and not in CLI you can open a filed handler to php://stderr and write the error messages there.

$fe = fopen('php://stderr', 'w');
fwrite($fe, 'error message');
hakre
  • 178,314
  • 47
  • 389
  • 754
mhitza
  • 5,399
  • 2
  • 26
  • 51
9

If you want the error messages sent by the php interpreter should go to the stderr-pipe, you must set display_errors to stderr

KingCrunch
  • 119,075
  • 18
  • 142
  • 167
2

This is required to return from PHP realm into shell environment in order to parse properly error message. You still need to exit(1) or whatever integer in order to return exit status code from PHP to shell.

fwrite(STDERR, 'error message'); //output message into 2> buffer
exit(0x0a); //return error status code to shell 

Then, your crontab entry will look like:

30 3 * * * /usr/bin/php /full/path/to/phpFile.php >> /logdir/fullpath/journal.log 2>> /logdir/fullpath/error_journal.log
stamster
  • 747
  • 8
  • 18
1

You can also use file_put_contents() with "php://stderr" to output to standard error, like:

php -r 'file_put_contents("php://stderr", "Hiya, PHP!\n"); echo "Bye!\n";' 1>/dev/null

which outputs "Hiya, PHP!\n" to standard error and nothing to standard output when executed in a Bash shell.

Mark Leighton Fisher
  • 5,431
  • 2
  • 14
  • 26