Book HomePHP CookbookSearch this book

18.22. Passing Input to a Program

18.22.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.

18.22.2. Solution

Open a pipe to the program with popen( ) , write to the pipe with fputs( ) or fwrite( ), then close the pipe with pclose( ):

$ph = popen('program arg1 arg2','w')          or die($php_errormsg);
if (-1 == fputs($ph,"first line of input\n"))  { die($php_errormsg); }
if (-1 == fputs($ph,"second line of input\n")) { die($php_errormsg); }
pclose($ph)                                   or die($php_errormsg);

18.22.3. Discussion

This example uses popen( ) to call the nsupdate command, which submits Dynamic DNS Update requests to name servers:

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

Two commands are sent to nsupdate via popen( ). The first deletes the test.example.com A record, and the second adds a new A record for test.example.com with the address 192.168.1.1.

18.22.4. See Also

Documentation on popen( ) at http://www.php.net/popen and pclose( ) at http://www.php.net/pclose; Dynamic DNS is described in RFC 2136 at http://www.faqs.org/rfcs/rfc2136.html.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.