System Calls in php

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 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 this program in, 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";
	echo "<pre>";
	foreach($output as $line) echo "$line\n";

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.


You may also like...