[ Team LiB ] Previous Section Next Section

Running Commands with exec()

exec() is one of many functions that enable you to pass commands to the shell. The function requires a string representing the path to the command you want to run. It also optionally accepts an array variable that is populated with the command's output and a scalar variable that is populated with the command's return value.

To get a listing for the current working directory, for example, you might pass exec() the command "ls -al .". We do this in Listing 21.4 (line 7), printing the result to the browser.

Listing 21.4 Using exec() to Produce a Directory Listing
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 21.4 Using exec() to Produce a Directory Listing</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: exec( "ls -al .", $output, $return );
12: print "<p>Returned: $return</p>";
13: foreach ( $output as $file ) {
14:   print "$file<br />";
15: }
16: ?>
17: </div>
18: </body>
19: </html>

Figure 21.2 shows the output from Listing 21.4.

Figure 21.2. Using exec() to produce a directory listing.

graphics/21fig02.jpg

Notice that the ls command returns 0 on success. If it were unable to find or read the directory passed to it, it would have returned 1.

Once again, we have reinvented the wheel to a certain extent with this example. We could have used the opendir() and readdir() functions to acquire a directory listing. Sometimes, however, a command on your system can achieve an effect that would take a long time to reproduce using PHP's functionality. You might have created a shell or Perl script that performs a complex task. If speed of development is an important factor in your project, you might decide that it is worth calling the external script instead of porting it to PHP, at least in the short term. Remember, though, that calling an external process always adds an overhead to your script in terms of both time and memory usage.

    [ Team LiB ] Previous Section Next Section