Redirecting output into STDERR in PHP console script

Recently I needed to send output from PHP console script into STDERR instead of STDOUT. Usually you would do it with an I/O redirection “COMMAND >&2″, but in this case it was not possible. A solution was pretty easy though – output buffer callback function which were redirecting output into STDERR and returning zero output for STDOUT.

Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
 * Output calback function
 * Writes buffer into STDERR instead of STDOUT
 * @link http://de3.php.net/manual/en/function.ob-start.php
 * @param string $output
 * @return string
 */
function SvnHook_outputCallback($output)
{
    fwrite(STDERR, $output);
    return '';
}
 
// set output callback redirecting STDOUT to STDERR
ob_start('SvnHook_outputCallback');

Leave a Reply