PHP Files Reading Standard Error from a Program - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Files Reading Standard Error from a Program - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, July 11, 2019

PHP Files Reading Standard Error from a Program

PHP Files 


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)                        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. You do this by redirecting it to /dev/null on Unix and NUL on Windows:

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

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

No comments:

Post a Comment

Post Top Ad