Running Commands with exec()


Running Commands with exec()

The exec() function is one of several functions you can use to pass commands to the shell. The exec() function requires a string representing the path to the command you want to run, and optionally accepts an array variable that will contain the output of the command, and a scalar variable that will contain the return value (1 or 0). For example

 exec("/path/to/somecommand", $output_array, $return_val); 

Listing 13.4 uses the exec() function to produce a directory listing with the shellbased ls command.

Listing 13.4. Using exec() and ls to Produce a Directory Listing
 1: <?php 2: exec("ls -al .", $output_array, $return_val); 3: echo "Returned $return_val<br><pre>"; 4: foreach ($output_array as $o) { 5:    echo "$o "; 6: } 7: echo "</pre>"; 8: ?> 

In line 2, we issue the ls command using the exec() function. We place the output of the command into the $output_array array, and the return value in the $return_val variable. Line 3 simply prints the return value, while the foreach loop in lines 46 prints out each element in $output_array.

By the Way

The string in line 3 includes an opening <pre> tag, and on line 7 we provide a closing tag. This simply ensures that your directory listing will be readable, using HTML preformatted text.


If you save this code as exec_ls.php, place it in your document root, and access it with your Web browser, you may see something like Figure 13.1 (with your actual information, not mine, of course).

Figure 13.1. Output of exec_ls.php.


As wonderful as PHP is, there may come a time when you want to integrate some sort of functionality within your PHP-based application, but someone else has already written code in Perl that does the same thing. In cases like this, there's no need to reinvent the wheel, as you can simply use exec() to access the existing script and utilize its functionality. However, remember that calling an external process will always add some amount of additional overhead to your script, in terms of both time and memory usage.



Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

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