Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

18.23. Reading Standard Error from a Program

Problem

You want to read the error output from a program; for example, you want to capture the system calls displayed by strace(1) .

Solution

Redirect standard error to standard output by adding 2>&1 to the command line passed to popen( ) . Read standard output by opening the pipe in r mode:

$ph = popen('strace ls 2>&1','r') or die($php_errormsg);
while (!feof($ph)) {
    $s = fgets($ph,1048576)       or die($php_errormsg);
}
pclose($ph)                       or die($php_errormsg);

Discussion

In both the Unix sh and the Windows cmd.exe shells, standard error is file descriptor 2, and standard output is file descriptor 1. Appending 2>&1 to a command tells the shell to redirect what’s normally sent to file descriptor 2 (standard error) over to file descriptor 1 (standard output). fgets( ) then reads both standard error and standard output.

This technique reads in standard error but doesn’t provide a way to distinguish it from standard output. To read just standard error, you need to prevent standard output from being returned through the pipe. This is done by redirecting it to /dev/null on Unix and NUL on Windows:

// Unix: just read standard error
$ph = popen('strace ls 2>&1 1>/dev/null','r') or die($php_errormsg);

// Windows: just read standard error
$ph = popen('ipxroute.exe 2>&1 1>NUL','r') or die($php_errormsg);

See Also

Documentation on popen( ) at http://www.php.net/popen; see your popen(3) manpage for details about the shell your system uses with popen( ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata