Hướng dẫn php exec php script

(PHP 4, PHP 5, PHP 7, PHP 8)

Show

execExecute an external program

Description

exec(string $command, array &$output = null, int &$result_code = null): string|false

Parameters

command

The command that will be executed.

output

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().

result_code

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.

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

Warning

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

Arno van den Brink

13 years ago

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 &");  
    }
}
?>

dell_petter at hotmail dot com

13 years ago

(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;
    }
}
?>

krjdev at gmail dot com

11 months ago

Note for OpenBSD users:

In the default configuration from OpenBSD, PHP runs into a chroot. So the exec() command will not work. You will get a 127 (command not found) result code. The reason is, the shell (/bin/sh) is missing in chroot, but the exec() command requires the shell.

A quick and dirty solution is to copy /bin/sh (which is statically linked) in the chroot directory:
$ cp /bin/sh /var/www/bin
?>

(I have noticed this on OpenBSD 7.0 with PHP 8.0.11.)

Simon

7 years ago

Can’t get the output from your exec’d command to appear in the $output array?
Is it echo’ing all over your shell instead?

Append "2>&1" to the end of your command, for example:

exec("xmllint --noout ~/desktop/test.xml 2>&1", $retArr, $retVal);

Will fill the array $retArr with the expected output; one line per array key.

msheakoski @t yahoo d@t com

18 years ago

I too wrestled with getting a program to run in the background in Windows while the script continues to execute.  This method unlike the other solutions allows you to start any program minimized, maximized, or with no window at all.  llbra@phpbrasil's solution does work but it sometimes produces an unwanted window on the desktop when you really want the task to run hidden.

start Notepad.exe minimized in the background:

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("notepad.exe", 7, false);
?>

start a shell command invisible in the background:
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false);
?>

start MSPaint maximized and wait for you to close it before continuing the script:
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("mspaint.exe", 3, true);
?>

For more info on the Run() method go to:
http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp

ivk

1 year ago

result_code -1 could mean "Maximum number of file descriptors reached". Check count(get_resources('stream')) and ulimit -Sn

Farhad Malekpour

15 years ago

If you're trying to use exec in a script that uses signal SIGCHLD, (i.e. pcntl_signal(SIGCHLD,'sigHandler');) it will return -1 as the exit code of the command (although output is correct!). To resolve this remove the signal handler and add it again after exec. Code will be something like this:

...
pcntl_signal(SIGCHLD, 'sigHandler');
...
...
(more codes, functions, classes, etc)
...
...
// Now executing the command via exec
// Clear the signal
pcntl_signal(SIGCHLD, SIG_DFL);
// Execute the command
exec('mycommand',$output,$retval);
// Set the signal back to our handler
pcntl_signal(SIGCHLD, 'sigHandler');
// At this point we have correct value of $retval.

Same solution can apply to system and passthru as well.

Bob-PHP at HamsterRepublic dot com

16 years ago

exec strips trailing whitespace off the output of a command. This makes it impossible to capture signifigant whitespace. For example, suppose that a program outputs columns of tab-delimited text, and the last column contains empty fields on some lines. The trailing tabs are important, but get thrown away.

If you need to preserve trialing whitespace, you must use popen() instead.

Paul Sommer

6 years ago

I tried to execute a command in background under Windows.
After struggling for hours with all these half ready examples I would like to share the syntax I found working (for windows at least). This is not tested under Linux as there are more elegant ways to spawn a process.

Based on  the function from Arno van den Brink.

function execInBackground($cmd) {
    if (
substr(php_uname(), 0, 7) == "Windows"){
       
pclose(popen("start /B ". $cmd, "r"));
    }
    else {
       
exec($cmd . " > /dev/null &"); 
    }
}
?>

This works perfectly with e.g.
execInBackground('del c:\tmp\*.*')
?>

but the following does NOT work:
execInBackground('\"c:\path with spaces\my program.exe\"')
?>

Why?
When windows sees quotation marks (\") it thinks this is the window title, not the command.
So, when your command needs quotation marks you HAVE TO provide a window name first, like
execInBackground("\"title\"" "\"c:\path with spaces\my program.exe\")

Quotation marks are mandatiory for window title. Otherwise windows thinks this is the program name.

Weired, but "Hey! it's Windows!" :)

hans at internit dot NO_SPAM dot com

20 years ago

From what I've gathered asking around, there is no way to pass back a perl array into a php script using the exec function.

The suggestion is to just print out your perl array variables at the end of your script, and then grabbing each array member from the array returned by the exec function. If you will be passing multiple arrays, or if you need to keep track of array keys as well as values, then as you print each array or hash variable at the end of your perl script, you should concatenate the value with the key and array name, using an underscore, as in:

foreach (@array) print "(array name)_(member_key)_($_)" ;

Then you would simply iterate through the array returned by the exec function, and split each variable along the underscore.

Here I like to especially thank Marat for the knowledge. Hope this is useful to others in search for similar answer!

layton at layton dot tk

17 years ago

This is the second time this one got me, I thought someone else might find this note useful too.

I am creating a long running exec'd process that I can access with page submissions up to 2 hours later. The problem is this, the first time I access the page everything works like it should. The second time the web browser waits and waits and never gets any messages -- the CPU time is not affected so it is apparent that something is blocked.

What is actually happening is that all of the open files are being copied to the exec'd process -- including the network connections. So the second time I try to access the web page, I am being given the old http network connection which is now being ignored.

The solution is to scan all file handles from 3 on up and close them all. Remember that handles 0, 1, and 2 are standard input, standard output, and standard error.

elwiz at 3e dot pl

12 years ago

On Windows-Apache-PHP servers there is a problem with using the exec command more than once at the same time. If a script (with the exec command) is loaded more than once by the same user at the same time the server will freeze.
In my case the PHP script using the exec command was used as the source of an image tag. More than one image in one HTML made the server stop.
The problem is described here (http://bugs.php.net/bug.php?id=44942) toghether with a solution - stop the session before the exec command and start it again after it.

session_write_close

();
exec($cmd);
session_start();?>

juan at laluca dot com

11 years ago

I was trying to get an acceslist from a remote computer by executing cacls and parse it in php, all in a  Windows environment with Apache. First i discovered psexec.exe from Windows SysInternals.

But with the following line, I didn´t get anything, it get hunged, although from the command line it worked nice:

('c:\\WINDOWS\\system32\\psexec.exe \\192.168.1.224 -u myuser -p mypassword -accepteula cacls c:\\documents\\RRHH && exit', $arrACL ); ?>

To make it work I just followed the next steps:
- execute services.msc and find the apache service (In my case wampapache)
- Right button>Log On tab and change from Local System Account to a user created account, enter the username and the password and restart the service.

(I added this user to the administrators group to avoid permissions problems but its not recommended...)

It worked! And it may work with IIS too so try it if you have the same poblem....

Hope this helps someone, and sorry for my english

php dot reg at kjpetrie dot co dot uk

1 month ago

If you want to run the command in the background and also use escapeshellcmd() as recommended, ensure you do the redirection outside the brackets! These are things you do want the shell to interpret.

E.g. exec(escapeshellcmd('mycommand and arguments').' > /dev/null &');

alvaro at demogracia dot com

11 years ago

In Windows, exec() issues an internal call to "cmd /c your_command". This implies that your command must follow the rules imposed by cmd.exe which includes an extra set of quotes around the full command:

- http://ss64.com/nt/cmd.html

Current PHP versions take this into account and add the quotes automatically, but old versions didn't.

Apparently, the change was made in PHP/5.3.0 yet not backported to 5.2.x because it's a backwards incompatible change. To sum up:

- In PHP/5.2 and older you have to surround the full command plus arguments in double quotes
- In PHP/5.3 and greater you don't have to (if you do, your script will break)

If you are interested in the internals, this is the source code:

sprintf(cmd, "%s /c \"%s\"", TWG(comspec), command);

It can be found at http://svn.php.net/viewvc/ (please find php/php-src/trunk/TSRM/tsrm_win32.c, the comment system doesn't allow the direct link).

Hypolite Petovan

2 years ago

On Unix, to execute a command $cmd in the background, the one and only allowed standard output redirection syntax is "> /path/to/file &". No other valid standard output redirection syntax will allow a command to be ran in the background.

// The following will be ran in the background
exec($cmd . " > /path/to/file &"); // All the following will NOT be ran in the background
exec($cmd . " >> /path/to/file &");
exec($cmd . " &> /path/to/file &");
exec($cmd . " &>> /path/to/file &");
exec($cmd . " 2>&1 > /path/to/file &");
exec($cmd . " 2>&1 >> /path/to/file &");
?>

Martin Lakes

11 years ago

Took quite some time to figure out the line I am going to post next. If you want to execute a command in the background without having the script waiting for the result, you can do the following:

passthru("/usr/bin/php /path/to/script.php ".$argv_parameter." >> /path/to/log_file.log 2>&1 &");
?>

There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'log_file.log' file

Enojy!

bahri at bahri dot info

13 years ago

[NOTE BY danbrown AT php DOT net: The following is a Linux script that the contributor of this note suggests be placed in a file named 'pstools.inc.php' to execute a process, check if a process exists, and kill a process by ID.  Inspired by the Windows version at http://php.net/exec#59428 ]

  function PsExecute($command, $timeout = 60, $sleep = 2) {
       
// First, execute the process, get the process ID $pid = PsExec($command);

        if(

$pid === false )
            return
false; $cur = 0;
       
// Second, loop for $timeout seconds checking if process is running
       
while( $cur < $timeout ) {
           
sleep($sleep);
           
$cur += $sleep;
           
// If process is no longer running, return true; echo "\n ---- $cur ------ \n";

            if( !

PsExists($pid) )
                return
true; // Process must have exited, success!
       
} // If process is still running after timeout, kill the process and return false
       
PsKill($pid);
        return
false;
    }

    function

PsExec($commandJob) { $command = $commandJob.' > /dev/null 2>&1 & echo $!';
       
exec($command ,$op);
       
$pid = (int)$op[0];

        if(

$pid!="") return $pid;

        return

false;
    }

    function

PsExists($pid) { exec("ps ax | grep $pid 2>&1", $output);

        while( list(,

$row) = each($output) ) { $row_array = explode(" ", $row);
               
$check_pid = $row_array[0];

                if(

$pid == $check_pid) {
                        return
true;
                }

        }

        return

false;
    }

    function

PsKill($pid) {
       
exec("kill -9 $pid", $output);
    }
?>

dr_jones153 at hotmail dot com

14 years ago

If SAFE_MODE is on, and you are trying to run a script in the background by appending "> /dev/null 2> /dev/null & echo $!" to the command line, the browser will hang until the script is done.

My solution:

Create a shell script (ex. runscript.sh) which contains the execution line for the script you are trying to run in the background.
The runscript.sh is run by an exec() call without the redirect string, which is now placed in the runscript.sh.

runscript.sh will return almost immediately because output of the original script is redirected, and so will not hang your browser and the script runs fine in the background.