System Calls

Sometimes PHP will not have the function you need to perform a certain action, but the operating system it is running on may. In such cases, you can use the exec system call to do the job.

For example, to quickly view the contents of the current directory, you can use a program such as the one in Example 7-17. If you are on a Windows system, it will run as-is using the Windows dir command. On Linux, Unix, or Mac OS X, comment out or remove the first line and uncomment the second to use the ls system command. You may wish to type in this program, save it as exec.php, and call it up in your browser.

Example 7-17. Executing a system command
<?php // exec.php
$cmd = "dir";   // Windows
// $cmd = "ls"; // Linux, Unix & Mac

exec(escapeshellcmd($cmd), $output, $status);

if ($status) echo "Exec command failed";
else
{
    echo "<pre>";
    foreach($output as $line) echo "$line\n";
}
?>

Depending on the system you are using, the result of running this program will look something like this (from a Windows dir command):

Volume in drive C is HP
Volume Serial Number is E67F-EE11

Directory of C:\web

20/01/2011  10:34
            .
    20/01/2011  10:34
                ..
        19/01/2011  16:26               236 maketest.php
        20/01/2011  10:47               198 exec.php
        20/01/2011  08:04            13,741 smiley.jpg
        19/01/2011  18:01                54 test.php
        19/01/2011  16:59                35 testfile.txt
        20/01/2011  09:35               886 upload.php
                    6 File(s)        15,150 bytes
                    2 Dir(s)  382,907,748,352 bytes free

exec takes three arguments:

  1. The command itself (in the previous case, $cmd)

  2. An array in which the system will put the output from the command (in the previous case, $output)

  3. A variable to contain the returned status of the call (in the previous case, $status)

If you wish, you can omit the $output and $status parameters, but you will not know the output created by the call or even whether it completed successfully.

You should also note the use of the escapeshellcmd function. It is a good habit to always use this when issuing an exec call because it sanitizes the command string, preventing the execution of arbitrary commands should you supply user input to the call.

Warning

The system calling functions are typically disabled on shared web hosts, as they pose a security risk. You should always try to solve your problems within PHP if you can, and go to the system directly only if it is really necessary. Also be aware that going to the system is relatively slow, and you’ll need to code two implementations if your application is expected to run on both Windows and Linux/Unix systems.