Daniel Rench

programming, etc.

Because Nobody Has Ever Put the Phrase "print to STDERR in PHP" on a Web Page

I once thought I needed to write to STDERR in some PHP code. This particular phrase (quoted) returned zero documents on well-known search engines, so I felt compelled to do something about it.

PHP provides STDERR (and STDOUT and STDIN) but not when running under a web server. Since that’s the environment virtually all PHP code runs, they may as well not be there at all.

Thanks to Andy Bakun, I learned about PHP’s error_log() function. When called with one argument (a message string), it sends the string to the web server’s error log (when running under a web server), or to STDERR (when running from the command line). So I think it’s safe to say error_log() is PHP’s do-what-I-mean equivalent of writing to STDERR in any other language. Usually.

Depending on your php.ini settings, error_log() may be going to your syslog, or some log file, which has thrown me a few times. While debugging a Roundcube plugin, I was wondering why none of my error_log() output was making it to the web server’s log. Then I noticed this:

1
ini_set('error_log', $this->prop['log_dir'].'/errors');

It looks like maybe at one time STDERR, etc. worked as programmers would expect but the last word on that was “Not PHP problem –> bogus.”

So if you’re really, really determined to print to STDERR no matter what the environment or the ini settings, you have to open it yourself:

1
2
  $STDERR = fopen('php://stderr', 'w+');
  fwrite($STDERR, "some debug info\n");