[ Team LiB ] Previous Section Next Section

Running External Applications with passthru()

passthru() is similar to system() except that any output from the shell command you send is not buffered. This makes it suitable for running commands that produce binary as opposed to text data. passthru() accepts a shell command and an optional variable, which is filled with the return value of the command.

Let's construct an example. We want to create a script that outputs images as thumbnails and that can be called from HTML or PHP pages. We are going to let external applications do all the work so that our script will be simple. Listing 21.7 shows the code that locates the image and outputs the data to the browser.

Listing 21.7 Using passthru() to Output Binary Data
 1: <?php
 2: if ( isset( $_REQUEST['image'] ) && file_exists( $_REQUEST['image'] ) ) {
 3:   header( "Content-type: image/gif" );
 4:   $image = $_REQUEST['image'];
 5:   passthru(  "giftopnm $image |
 6:         pnmscale -xscale .5 -yscale .5 |
 7:         ppmquant 256 | ppmtogif" );
 8: } else {
 9:   print "The image ".$_REQUEST['image']." could not be found";
10: }
11: ?>

Notice that we have not used escapeshellcmd(). Instead, we have tested the user input against our file system on line 2 using the file_exists() function. We will not pass the $_REQUEST['image'] argument to the shell if the image requested does not exist. For additional security, we could also limit the extension we will accept and the directory that can be accessed.

In the call to passthru() on line 5, we issue a command that calls four commands. Note that for this script to work on your system, you must have these commands installed, and they must be available in your path. First, we call giftopnm, passing it the $image variable. This reads a GIF image and outputs data in portable anymap format. This output is piped to pnmscale, which scales the image to 50% of its original size. The output from pnmscale is in turn piped to ppmquant and ppmtogif, which convert the data to GIF palette and format. This data is finally output to the browser.

We can now call this script from any Web page:


<img src="listing21.7.php?image=<?php print urlencode("/path/to/image.gif") ?>">


    [ Team LiB ] Previous Section Next Section