Recipe 23.17. Passing Input to a Program

23.17.1. Problem

You want to pass input to an external program run from inside a PHP script. You might, for example, use a database that requires you to run an external program to index text and want to pass text to that program.

23.17.2. Solution

Open a pipe to the program with popen( ), write to the pipe with fputs( ) or fwrite( ), and then close the pipe with pclose( ) , as in Example 23-42.

Passing input to a program

<?php $ph = popen('/usr/bin/indexer --category=dinner','w') or die($php_errormsg); if (-1 == fputs($ph,"red-cooked chicken\n"))    { die($php_errormsg); } if (-1 == fputs($ph,"chicken and dumplings\n")) { die($php_errormsg); } pclose($ph)                                    or die($php_errormsg); ?>

23.17.3. Discussion

Example 23-43 uses popen( ) to call the nsupdate command, which submits Dynamic DNS Update requests to nameservers.

Using popen( ) with nsupdate

<?php $ph = popen('/usr/bin/nsupdate -k keyfile')               or die($php_errormsg); if (-1 == fputs($ph,"update delete A\n")) { die($php_errormsg); } if (-1 == fputs($ph,"update add 5 A\n"))                                                            { die($php_errormsg); } pclose($ph)                                               or die($php_errormsg); ?.

In Example 23-43, two commands are sent to nsupdate via popen( ). The first deletes the A record, and the second adds a new A record for with the address

23.17.4. See Also

Documentation on popen( ) at and pclose( ) at; Dynamic DNS is described in RFC 2136 at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: