- exec
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 20 notes
- How To Execute Shell Commands with PHP Exec and Examples?
- exec() Function Syntax
- Run External System Binary or Application
- Print Output
- Assign Return Value into Variable
- Return Complete Output as String with shell_exec()
- PHP shell_exec() Examples
- Return Complete Output as String with system()
- exec() Function vs shell_exec() Function
- 3 thoughts on “How To Execute Shell Commands with PHP Exec and Examples?”
exec
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n , is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec() .
If the result_code argument is present along with the output argument, then the return status of the executed command will be written to this variable.
Return Values
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
Returns false on failure.
To get the output of the executed command, be sure to set and use the output parameter.
Errors/Exceptions
Emits an E_WARNING if exec() is unable to execute the command .
Throws a ValueError if command is empty or contains null bytes.
Changelog
Version | Description |
---|---|
8.0.0 | If command is empty or contains null bytes, exec() now throws a ValueError . Previously it emitted an E_WARNING and returned false . |
Examples
Example #1 An exec() example
// outputs the username that owns the running php/httpd process
// (on a system with the «whoami» executable in the path)
$output = null ;
$retval = null ;
exec ( ‘whoami’ , $output , $retval );
echo «Returned with status $retval and output:\n» ;
print_r ( $output );
?>?php
The above example will output something similar to:
Returned with status 0 and output: Array ( [0] => cmb )
Notes
When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.
Note:
If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.
Note:
On Windows exec() will first start cmd.exe to launch the command. If you want to start an external program without starting cmd.exe use proc_open() with the bypass_shell option set.
See Also
- system() — Execute an external program and display the output
- passthru() — Execute an external program and display raw output
- escapeshellcmd() — Escape shell metacharacters
- pcntl_exec() — Executes specified program in current process space
- backtick operator
User Contributed Notes 20 notes
This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.
function execInBackground ( $cmd ) <
if ( substr ( php_uname (), 0 , 7 ) == «Windows» ) <
pclose ( popen ( «start /B » . $cmd , «r» ));
>
else <
exec ( $cmd . » > /dev/null &» );
>
>
?>
(This is for linux users only).
We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.
This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).
You may use it to start a process or join an exisiting PID process.
// You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
$process = new Process ( ‘ls -al’ );
// or if you got the pid, however here only the status() metod will work.
$process = new Process ();
$process . setPid ( my_pid );
?>
// Then you can start/stop/ check status of the job.
$process . stop ();
$process . start ();
if ( $process . status ()) echo «The process is currently running» ;
>else echo «The process is not running.» ;
>
?>
/* An easy way to keep in track of external processes.
* Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
* @compability: Linux only. (Windows does not work).
* @author: Peec
*/
class Process private $pid ;
private $command ;
public function __construct ( $cl = false ) if ( $cl != false ) $this -> command = $cl ;
$this -> runCom ();
>
>
private function runCom () $command = ‘nohup ‘ . $this -> command . ‘ > /dev/null 2>&1 & echo $!’ ;
exec ( $command , $op );
$this -> pid = (int) $op [ 0 ];
>
public function setPid ( $pid ) $this -> pid = $pid ;
>
public function getPid () return $this -> pid ;
>
public function status () $command = ‘ps -p ‘ . $this -> pid ;
exec ( $command , $op );
if (!isset( $op [ 1 ]))return false ;
else return true ;
>
public function start () if ( $this -> command != » ) $this -> runCom ();
else return true ;
>
public function stop () $command = ‘kill ‘ . $this -> pid ;
exec ( $command );
if ( $this -> status () == false )return true ;
else return false ;
>
>
?>
How To Execute Shell Commands with PHP Exec and Examples?
Php provides web-based functionalities to develop web applications. But it also provides system related scripting and execution features. The exec() function is used to execute an external binary or program from a PHP script or application. In this tutorial, we will look at different use cases and examples of exec() function like return value, stderr, shell_exec, etc.
exec() Function Syntax
The PHP exec() syntax is like below where single parameter is mandatory and other parameters are optional.
exec(string COMMAND, array OUTPUT, int RETURN_VARIABLE);
- COMMAND is the command we want to execute with the exec() function. The command should be a string value or variable. COMMAND is a mandatory parameter.
- OUTPUT is the output of the COMMAND execution. OUTPUT is an array that can hold multiple values or lines. OUTPUT is optional where it can be omitted.
- RETURN_VARIABLE is the return value of the given COMMAND. RETURN _VALUE is generally the process status of the command. RETURN_VALUE is an integer and optional to use.
Run External System Binary or Application
We will start with a simple example. We will provide the command we want to run on the local operating system. In this example, we will create a directory named data . This directory will be created in the current working path. We can also specify the path explicitly like /var/data .
We can list the created directory with Linux file command like below. We will also provide the directory name because exec() function will only show the last line of the output. We will use echo to print the command output.
Print Output
We have already looked at printing output but I want to explain more about printing output. exec() function output or return can be printed with echo but the printed part will be only last line. So in a multi-line output, we can not see the output with echo . If we want to see the whole output we should use the system() function which will be explained below.
But we can use the output parameter like below. In this example, we will put command output to the o . The output parameter is in array type so we will use print_r to print output.
From the output we can see that the executed ls command output is stored in the variable named $o as an array. Every item is a files or folder which is located under the current working directory.
Assign Return Value into Variable
Using echo is not a reliable way to get the return value. We can use variables to set return values and use whatever we want. In this example, we will set the process return value to the variable named v.
Return Complete Output as String with shell_exec()
PHP language provides different functions as an alternative to exec() . We can use the shell_exec() function which will create a shell process and run given command. In this example, we will look at ls command and print output. With the shell_exec() function we can not get the return value of the shell process or command.
PHP shell_exec() Examples
In this part, we will make more examples about the PHP shell_exec() function. We will run the different system and Linux commands like date , whoami , ifconfig and mkdir .
echo shell_exec('date'); echo shell_exec('whoami'); echo shell_exec('ifconfig');
Return Complete Output as String with system()
Another similar function is system() . system() function displays output directly without using echo or print . In this example, we will run the ls command again.
exec() Function vs shell_exec() Function
PHP also provides the shell_exec() function which is very similar to the exec() function. The main difference is shell_exec() function accepts a single parameter which is a command and returns the output as a string.
//Execude command in the shell with PHP exec() function //put the output to the $output variable exec("uname -a",$output,$return_val); print_r($output); //Execude command in the shell with PHP shell_exec() function //put the output into $out variable $out = shell_exec("uname -a"); echo $out;
3 thoughts on “How To Execute Shell Commands with PHP Exec and Examples?”
Commands like ls work fine but creating a directory in not working for me not sure if I need to change any permissions or anything.
Any idea? Reply
Almost certainly some kind of permissions problem. The user running the PHP script needs to have the ability to do what the command wants to do. Try creating a directory in /tmp and see if that works. Make sure your command is /bin/sh compatible since that’s hardcoded into PHP. Reply
late but… write the command with path for success:
exec(“/usr/bin/mkdir dir”,$output,$return_val); Reply