Executing Commands through PHP (Linux & Windows)

Its amazing to see PHP interact with the Operating System, as we have Command Prompt in Windows and have the Terminal in Linux PHP can externally execute commands to it and return you the output or null if an error is found.

Basically we have 3 common functions for running commands in PHP, which are:

  1. shell_exec()
  2. exec()
  3. passthru()
  4. Execution Operator (“)

What are the differences between the 3 functions?

Well, I have ran 3 of them and came to notice some differences between them but the one I use mostly is the shell_exec();

  • Shell_exec(): This function executes commands and returns output completely as string which you can manipulate with explode() function if you want a specific data from it 🙂 . In your Windows Server, XAMPP and WAMP try this
<?php
$cmd = shell_exec("ipconfig");

echo '<pre>'.$cmd.'</pre>';
?>

Or Linux try this

<?php
$cmd = shell_exec("ls -a");

echo '<pre>'.$cmd.'</pre>';
?>

You see the output is returned as string 🙂

  • exec(): Now this one returns the last line of a command if its more than a line as a string, change the shell_exec() in the above code to exec() and see that its return is the last line of the command as string 🙂
  • passthru(): I should say this is the same as shell_exec() because I noticed no changes so far when I ran it, but if command returns a binary data, you can set header to content-type: image/jpeg, the page content turns to a JPEG image. Which means it returns binary data if any but shell_exec doesn’t 🙂
  • Execution Operator (“): This is the same with shell_exec(), just that its not a function but an operator which is called an execution operator and returns output as string (Note: its different from single quote (‘)), try this:
<?php
//In Windows, Linux should try `ls -a`
$cmd = `ipconfig`;

echo '<pre>'.$cmd.'</pre>';
?>

The above is the little I know about them, any suggestion is accepted via comment 🙂