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 which will contain the output of the command, and a scalar variable which will contain the return value (1 or 0). For example:

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

Listing 12.4 uses the exec() function to produce a directory listing with the shell-based ls command.

Listing 12.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>"; 4: foreach ($output_array as $o) { 5: echo "$o <br>"; ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.