PHP's Program Execution Functions This section introduces several functions (in addition to the backticks execution operator) used to execute system-level programs via a PHP script. Although at first glance they all appear to be operationally identical, each offers its own syntactical nuances. exec() string exec (string command [, array output [, int return_var]]) The exec() function is best-suited for executing an operating system-level application (designated by command) intended to continue executing in the server background. Although the last line of output will be returned, chances are that you'd like to have all of the output returned for review; you can do this by including the optional parameter output, which will be populated with each line of output upon completion of the command specified by exec(). In addition, you can discover the executed command's return status by including the optional parameter return_var. Although we could take the easy way out and demonstrate how exec() can be used to execute an ls command (dir for the Windows folks), returning the directory listing, it's more informative to offer a somewhat more practical example: how to call a Perl script from PHP. Consider the following Perl script (languages.pl): #! /usr/bin/perl The Perl script is quite simple; no third-party modules are required, so you could test this example with little time investment. If you're running Linux, chances are very good that you could run this example immediately, because Perl is installed on every respectable distribution. If you're running Windows, check out ActiveStates (http://www.activestate.com/) ActivePerl distribution. Like languages.pl, the PHP script shown here isn't exactly rocket science; it simply calls the Perl script, specifying that the outcome be placed into an array named $results. The contents of $results are then output to the browser. <?php The results are as follows: --------------------------------------------perl system() string system (string command [, int return_var]) The system() function is useful when you want to output the executed command's results. Rather than return output via an optional parameter, as is the case with exec(), the output is returned directly to the caller. However, if you would like to review the execution status of the called program, you need to designate a variable using the optional parameter return_var. For example, suppose you'd like to list all files located within a specific directory: $mymp3s = system("ls -1 /home/jason/mp3s/"); Or, revising the previous PHP script to again call the languages.pl using system(): <?php
blog comments powered by Disqus |
|
|
|
|
|
|
|