Executing shell command in php

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 .
Читайте также:  Выравнивание абзаца с помощью атрибута Style

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 );
?>

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 in PHP

There are times when you need to run a shell command from inside a PHP program. This can be for several reasons such as running terminal-based programs or running common terminal commands like ls . PHP can execute any shell command and return its output as a string or array if needed.

In this tutorial, we will learn how to execute shell commands in PHP with examples.

PHP exec() Function Syntax

exec(command, output, return_variable) 

Here is what each parameter is used for in exec()

  • command — the only required argument in exec() . It is the terminal command to run
  • output — do something with the output of the command. Can be used to return the output back into the PHP program as a string
  • return_variable — put the output in the variable defined in this parameter

Make a Directory Using exec()

In this example, we will create a directory. We will do this using the Linux mkdir command and passing in the name of the directory we want to create.

The above command will create a directory in the same directory as the PHP file that executed it.

To create a directory in a different location on the system pass in a path before the name of the directory. This can be an absolute path (relative to root) or a relative path to the location of your program.

exec('mkdir /var/www/sites/skillsugar/public/test'); 

Using a Variable inside exec()

It is possible to pass variables into exec() by closing the ‘ (single quote) or » (double quote) and concatenating the variable in using a . (dot).

$file_name = 'new_dir'; exec('mkdir /home/vagrant/sites/skillsugar/public/' . $file_name); 
$dir_name = 'new_dir'; exec('mkdir ' . $dir_name . '/file.txt'); 

Printing the Output from exec()

You can simply echo the output.

Multi-line Output from exec()

You will notice that the above example only prints the last line from the ls command. To get all the lines we can set an output variable in the second parameter of exec() and then print the array containing all the lines.

Array ( [1] => build [2] => cgi-bin [3] => css [4] => error_log [5] => example.txt #. [16] => test [17] => test.php [18] => test2 [20] => translations [21] => web.config ) 

Set a Return Variable

To get what the terminal command returned we can set a variable in the third parameter of exec() .

Return Output as a String with the PHP shell_exec() Function

To return a complete string from a shell execute command in PHP use the shell_exec() function instead. It works in the same way to exec() except it takes no arguments and will return the complete output as a string.

build cgi-bin css error_log example.txt #. test test.php test2 translations web.config 

PHP system() Function

The system() PHP function works just like shell_exec() except you don’t need to print or echo the output string as it does this for you.

build cgi-bin css error_log example.txt #. test test.php test2 translations web.config 

Conclusion

You now know how to execute a shell command in three different ways using PHP. exec() give you the most flexibility, but you will have to pass a second argument to get the complete output as a string. system() is the most basic way to execute a command and get the complete output but has limited functionality.

Источник

Оцените статью