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.
<?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:
The command itself (in the previous case,
$cmd
)An array in which the system will put ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.