Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search
(current page)
Focus search box
Description
exec
(
string
$command
,
array
&$output
=
null
,
int
&$result_code
=
null
):
string
|
false
exec()
executes the given
command
.
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.
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.
Example #1 An
exec()
example
<?php
// 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
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.
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
¶
15 years ago
This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.
<?php
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
¶
14 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.
<?php
$process
= new
Process
(
'ls -al'
);
$process
= new
Process
();
$process
.
setPid
(
my_pid
);
?>
<?php
$process
.
stop
();
$process
.
start
();
if (
$process
.
status
()){
echo
"The process is currently running"
;
}else{
echo
"The process is not running."
;
}
?>
<?php
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
;
}
}
?>
Simon
¶
8 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
¶
19 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:
<?php
$WshShell
= new
COM
(
"WScript.Shell"
);
$oExec
=
$WshShell
->
Run
(
"notepad.exe"
,
7
,
false
);
?>
start a shell command invisible in the background:
<?php
$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:
<?php
$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
Farhad Malekpour
¶
16 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.
krjdev at gmail dot com
¶
1 year 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:
<?php
$
cp
/
bin
/
sh
/var/
www
/
bin
?>
(I have noticed this on OpenBSD 7.0 with PHP 8.0.11.)
Paul Sommer
¶
7 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.
<?php
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.
<?php
execInBackground
(
'del c:\tmp\*.*'
)
?>
but the following does NOT work:
<?php
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!" :)
layton at layton dot tk
¶
18 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.
Hypolite Petovan
¶
3 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.
<?php
exec
(
$cmd
.
" > /path/to/file &"
);
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 &"
);
?>
Bob-PHP at HamsterRepublic dot com
¶
17 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.
elwiz at 3e dot pl
¶
13 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.
<?php
session_write_close
();
exec
(
$cmd
);
session_start
();
?>
hans at internit dot NO_SPAM dot com
¶
21 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!
Martin Lakes
¶
12 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:
<?php
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!
juan at laluca dot com
¶
12 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:
<?php exec
(
'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
tsmtgdi at gmail dot com
¶
27 days ago
Please be aware that EXEC ignore the stderr!
So something like
mkdir /impossible path
Will fail, and show nothing, you must use
mkdir /impossible 2>&1
to properly capture the error message
ELSE
if executed in CLI, will just print on the terminal, if executed on a browser is lost.
I strongly suggested those notes to be added in the main description, and not lost in a comment at the bottom.
no at mail dot com
¶
7 months ago
<this note copied from system page>
This is for WINDOWS users. I am running apache and I have been trying for hours now to capture the output of a command.
I'd tried everything that is written here and then continued searching online with no luck at all. The output of the command was never captured. All I got was an empty array.
Finally, I found a comment in a blog by a certain amazing guy that solved my problems.
Adding the string ' 2>&1' to the command name finally returned the output!! This works in exec() as well as system() in PHP since it uses stream redirection to redirect the output to the correct place!
<?php
exec
(
"yourCommandName 2>&1"
,
$output
);
var_dump
(
$output
);
?>
alvaro at demogracia dot com
¶
12 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).
bahri at bahri dot info
¶
14 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
]
<?php
function
PsExecute
(
$command
,
$timeout
=
60
,
$sleep
=
2
) {
$pid
=
PsExec
(
$command
);
if(
$pid
===
false
)
return
false
;
$cur
=
0
;
while(
$cur
<
$timeout
) {
sleep
(
$sleep
);
$cur
+=
$sleep
;
echo
"\n ----
$cur
------ \n"
;
if( !
PsExists
(
$pid
) )
return
true
;
}
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
¶
15 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.