Running Commands with system() or passthru()
The system() function is similar to the exec() function in that it launches an external application, and it utilizes a scalar variable for storing a return value:
system("/path/to/somecommand", $return_val);
The system() function differs from exec() in that it outputs information directly to the browser, without programmatic intervention. The following snippet of code uses system() to print a man page for the man command, formatted with the <pre></pre> tag pair:
<?php
echo "<pre>";
system("man man | col b", $return_val);
echo "</pre>";
?>
Similarly, the passthru() function follows the syntax of the system() function, but it behaves differently. When using passthru(), any output from the shell command is not buffered on its way back to you; this is suitable for running commands the produce binary data instead of simple text data. An example of this would be to use shell tools to locate an image and send it back to the browser, as seen in Listing 12.5.
Listing 12.5 Using passthru() to Output Binary Data
1: <?php
2: if ((isset($_GET[imagename])) && (file_exists($_GET[imagename]))) {
3: header("Content-type: image/gif");
4: passthru("giftopnm $_GET[imagename] | pnmscale -xscale .5 -yscale .5 |
ppmtogif");
5: } else {
6: echo "The image $_GET[imagename] could not be found";
7: }
8: ?>
![]() | The shell utilities used in this script, giftopnm, pnmscale and ppmtogif may or may not be installed on your system. If they are not, don''t worry about it; just use this listing to understand the concept of using the passthru() function. |
This script would be called from HTML like the following:
<img src=" echo urlencode("test.gif") ?>">
In line 2 of Listing 12.5, the user input is tested to ensure that the file in question (test.gif, according to the HTML snippet) exists. Because the script will be outputting GIF data to the browser, the appropriate header is set on line 3. On line 4, the passthru() function consecutively executes three different commandsgiftopnm, pnmscale, and ppmtogif, which scales the image to 50% of its original height and width. The output of the passthru() commandthat is, the new image datais sent to the browser.