13.3 Opening a Pipe to Another Program


You want to open a pipe to a process and read or write data to it.

Technique

Use the popen() and pclose() functions as substitutes for fopen() and fclose() . You can then treat the pipe just like a file:

 <?php $pp = popen("/usr/sbin/sendmail -t", "w") or die("Cannot Fork Sendmail"); fputs($pp, "To: sterling@designmultimedia.com\r\n"); fputs($pp, "Reply-to: $senders_email\r\n"); fputs($pp, "From: $senders_email\r\n"); fputs($pp, "Subject: The Results of your form\r\n\r\n"); fputs($pp, "$senders_email sent the following comments:\r\n"); fputs($pp, $comments); pclose($pp) or die("Cannot close pipe to Sendmail"); ?> 

Comments

In this example, we open a pipe to the sendmail process, and then print the information we want sendmail to deal with to the pipe handle ( $pp ). Perl programmers might have noticed that this is a PHP version of the classic way of sending form results by e-mail through Sendmail.

When working with pipes, all data must be in the format in which the other program wants it, because pipes are relatively low level. For example, we terminate each line in the example with both a carriage return and a newline so that the mail sent is compatible with both DOS- and UNIX-based systems.

Pipes allow for the two way exchange of data, meaning you can both write to a pipe and then retrieve data from a pipe. This makes them a powerful addition to PHP's set of functions for IPC. Examine the following, which reads the output of a Perl script and prints it to the Web browser:

 <?php $pp = popen("./some_perl_script.pl", "r")    or die("cannot fork"); while ($line = fgets($pp, 1024)) {     print $line; } ?> 


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