13.1 Capturing the Output of Another Program


You want to capture the output of another program, such as the output of the date program or the whereis program.

Technique

The simplest solution is to use backticks to capture the output of a program into a variable:

 <?php $current_date = `date`; ?> 

Or, open a pipe to the program from which you want to capture output:

 <?php $pp = popen('date', 'r'); while ($line = fgets($var, 1024)) {     $output .= $line; } pclose($pp); ?> 

Comments

The miracle of backticks is that they provide a convenient and easy way to assign the output of a program to a variable. Perhaps some of you are saying that they are too good to be true. No, that's all there is to it. However, there's one catch: Using backticks takes considerably longer than other related procedures simply because the backticks format the output of the program and place it all in the variable to which the output is being assigned.

In the second method, we open a pipe to the program. We can then manipulate this pipe as if it were a file, meaning that not only can we get output from the pipe as if it were a file, but we can also send data through the pipe via fputs() .

There is another method of collecting the output of your program with PHP, which is via the exec () function. The exec() function will open a pipe to a program and place all the output of the program into an array of lines (the array to fill is the second argument):

 <?php exec('date', $output); print implode("\n", $output); ?> 

Gotcha

I want to stress this: Whenever interprocess communication is involved, if you are collecting data from your users and executing it on the shell, always use the EscapeShellCmd() function. The EscapeShellCmd() function escapes all the characters that might cause your system harm.




PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net