PHP – Program execution functions

This post introduces several functions (in addition to the backticks execution operator) used to execute system-level programs via a PHP script. Although at first glance they all appear to be operationally identical, each offers its own syntactical nuances.


string exec (string command [, array output [, int return_var]])

The exec() function is best-suited for executing an operating system-level application (designated by command) intended to continue executing in the server background. Although the last line of output will be returned, chances are that you’d like to have all of the output returned for review; you can do this by including the optional parameter output, which will be populated with each line of output upon completion of the command specified by exec(). In addition, you can discover the executed command’s return status by including the optional parameter return_var.

Although we could take the easy way out and demonstrate how exec() can be used to execute an ls command (dir for the Windows folks), returning the directory listing, it’s more informative to offer a somewhat more practical example: how to call a Perl script from PHP. Consider the following Perl script (

#! /usr/bin/perl
my @words = qw[one two three four five]; foreach $word (@words) {
print $word.”

The Perl script is quite simple; no third-party modules are required, so you could test this example with little time investment. If you’re running Linux, chances are very good that you could run this example immediately, because Perl is installed on every respectable distribution.
If you’re running Windows, check out ActiveStates ( ActivePerl distribution.

The results are as follows:



string system (string command [, int return_var])

The system() function is useful when you want to output the executed command’s results. Rather than return output via an optional parameter, as is the case with exec(), the output is returned directly to the caller. However, if you would like to review the execution status of the called program, you need to designate a variable using the optional parameter return_var.

For example, suppose you’d like to list all files located within a specific directory:

$myimages = system(“ls -1 /home/user/images/”);

Or, revising the previous PHP script to again call the using system():

Leave a Reply

Your email address will not be published. Required fields are marked *