O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required