exec

Description

stringexec
( string$command
[, array&$output
[, int&$return_var
]] )

exec() executes the given
command.

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

return_var

If the return_var 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.

To get the output of the executed command, be sure to set and use the
output parameter.

Examples

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)echo exec('whoami');?>

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.

Note: When
safe mode is enabled, you can only
execute files within the safe_mode_exec_dir.
For practical reasons, it is currently not allowed to have ..
components in the path to the executable.

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

<?php// 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."; }?>

<?php/* 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;

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.

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:

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.

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 signalpcntl_signal(SIGCHLD, SIG_DFL);// Execute the commandexec('mycommand',$output,$retval);// Set the signal back to our handlerpcntl_signal(SIGCHLD, 'sigHandler');// At this point we have correct value of $retval.

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!

If you're having problems with any of the exec(), system() etc. functions not working properly on windows, finding the cause can be very frustrating, as is hard to diagnose.

I've found the free Process Monitor from Sysinternals (procmon.exe from live.sysinternals.com) to be VERY helpful here. You can monitor anything done by e.g. php.exe, cmd.exe and yourprogram.exe and it will list every access to files, registry etc. with return codes. You usually find some ACCESS DENIED somehwer in the log, correct the file's permissions and it works.

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

When calling exec() from within an apache php script, make sure to take care of stdout, stderr and stdin (as in the example below). If you forget this and your shell command produces output the sh and apache deamons may never return (they will normally time out after a few minutes). From the calling web page the script may seem to not return any data.

If you want to start a php process that continues to run independently from apache (with a different parent pid) use nohub. Example:

I was having trouble using the PHP exec command to execute any batch file. Executing other commands (i.e., "dir") works fine). But if I executed a batch file, I receieved no output from the exec command.

The server setup I have consists of Windows Server 2003 server running IIS6 and PHP 5.2.3. On this server, I have:

1. Granted execute permissions to the Internet User on c:\windows\system32\cmd.exe.2. Granted Everyone->Full Control to the directory in which the batch file is written.3. Granted Everyone->Full Control on the entire c:\cygwin\bin directory and its contents.4. Granted the Internet User "log on as batch" permissions.5. Specified the full path to each file being executed.6. Tested these scripts running from the command line on the server and they work just fine.7. Ensured that %systemroot%\system32 is in the system path.

It turns out that even with all of the above in place on the server, I had to specify the full path to cmd.exe in the exec call.

When I used the call:$output = exec("c:\\windows\\system32\\cmd.exe /c $batchFileToRun");

then everything worked fine. In my situation, $batchFileToRun was the actual system path to the batch file (i.e., the result of a call to realpath()).

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.

I am posting this as I see quite a few people looking to create a web based interface to their MP3 player (XMMS or really what ever you want to call from the command line) on Linux. Alas, I am not the only one, and I did not think of it first ( suppose I have to result to other get rich quick schemes). And even if there were a direct downloadable utility (as there is XMMS-Control) you, like me, probably want the bowl of porage that is just right. Which means you want to make your own because current versions of X, Y, or Z just don't do what you want.

Most of the hard work is at the linux command shell (ugh! - I heard that! Drop and give me 20 command line scripts!)

login as root

ensure /dev/dsp has the proper access privilegeschmod a+rw /dev/dsp

add apache to the local list of users for the xserver.xhost +local:apache@

You should see the following if apache is not added to the xserver.

Xlib: connection to ":0.0" refused by serverXlib: No protocol specified

** CRITICAL **: Unable to open display

And I am sure that error is as clear to you as it was to me!

NOTE !!! only change the following for testing purposes so that you can su to apache from root and test xmms !!!!

Temporarily change the line

apache:x:48:48:Apache:/var/www:/sbin/nologin

Toapache:x:48:48:Apache:/var/www:/bin/bash

so that you can test out apache access to the Xserver and XMMS.

su apachexmms!!! Play a file - Don't just read this actually play a file!!! The reason is that if it fails xmms will likely give an error you can track down like a greyhound chases that little bunny at the dog track! (speaking of get rich quick schemes)

And for the grand finale!

If you can call xmms from the command line you can likely do the following (unless you are running php in safe mode). Ensure that the wav, mp3, or whatever you decide to test it with is accessible to apache. I put the file into /var/www/html/icould.wav and chmod a+rw icould.wav

I had a script calling a powershell script in one function. It worked fine on XP but when we moved to Windows 7 it stopped working. The script seemed to hang and expect a carriage return before it continued.

Adding "echo . |" before calling powershell gave it the desired carriage return:

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.

[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 ]

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.

If you're on windows, advice to use Sysinternals (procmon.exe from live.sysinternals.com) is pretty darn good. Saved me also a lot of time, and keeped me from having to open up my entire server to the anonymous web user.

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.

The article on exec() tells you to use passthrough() if you want to get more than the last line of output from a command. However mor appropriate would be to refer to shell_exec(), since passthrough will output the result (just like print()) whereas shell_exec() will give the whole output as a $string, which is more likely the thing you want if you are not content with exec() delivering only the last line as $string

To my way of thinking, it is a good idea to execute programs from the cgi-bin directory of the Web server, to get a little control over configuring a system (at install time, a pointer to the actual program can be symlinked from the cgi-bin directory and the code won't ever have to be changed). If you'd like to do this, under Apache at least, the following should work:

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.

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

but the following does NOT work:<?phpexecInBackground('\"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, likeexecInBackground("\"title\"" "\"c:\path with spaces\my program.exe\")

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

Well, after hours of fighting with output redirection, input redirection, error redirection, session_write_close (), blah blah blah, I think I found an easy way to execute a program in background. I used the following command:

Proc_Close (Proc_Open ("./command --foo=1 &", Array (), $foo));

With the second argument you tell proc_open not to open any pipe to the new process, so you don't have to worry about anything. The third argument is only needed because it's not optional. Also, with the '&' operator the program runs in background so the control is returned to PHP as soon as Proc_Close is executed (it doesn't have to wait).In my case I don't use the user session in the executed script (there's no way it can be identified if it is not sended as a cookie or URL) so there's no need for session_write_close (correct me if I'm wrong with this).It worked for me.

Task: Invoke psexec from php to execute a command on a remote computer.Environment:-Windows XP Professional, Service Pack 3-Apache 2.2 Installed (I used the version bundled in XAMP 1.6.6a)-The executable to be run must be in your system PATH!!PHP Script:<?phpexec ("psexec -u someusername -p somepassword -c \\\\someipaddressORHostname someprogram.exe");#sample command#exec ("psexec -u JoeShmoe -p ShrimpLover529 -c \\\\192.168.22.156 cleanfiles.exe");?>Problems:-I kept getting Access Denied ErrorsObservation(s):-I noticed that when I put that same psexec command in a batch file and started that batch file with the system account, I would get the same error-This lead me to the causeCause:-Apache was running as the system account, and so any process invoked by php was started as the system account-Starting a batch file that accesses a remote computer using the local system account is a NO NO (at least for my setup)Solution:-Configure the Apache service to start as an account other than system (It must have appropriate permissions on the local computer)Start-->Run-->Services.msc-->RightClick Apache Service-->Properties-->Logon Tab-->Enter in value for "Log on As"

Now load the same php page again.Look at the error.log againYou should see an error code 0 returned for the process executed, indicating a successful run

echo y | echo x does not become echo "y | echo x". It essentially becomes echo "y" "|" "echo" "x". The entire string is passed through escapeshellcmd(), which effectively splits arguments at spaces. Note that this makes it impossible to reliably pass arguments containing spaces to exec() in safe_mode. Since 4.3.3 escapeshellcmd() tries to pass quoted arguments through (so you could try exec("cmd 'arg 1' 'arg 2'")), but not on win32, and will still wrongly backslash escape any punctuation characters inside the quotes.

Not only can the path not contain '..' components, but no directory or filename can contain the string '..'. e.g. /path/to/my..executable will refuse to run.

I had a bit of trouble using exec with Windows when passing a parameter to a PHP script file. I found I needed to create a Windows batch "wrapper" file to get the script file to accept the optional argument.

I just want to add a note to the function "jonas DOT info AT gmx DOT net" contributed to keep processes running in the background.

Not like with the other exec/system/passthru etc. functions if you want to execute a batch file on a MS-machine you need to add a simple exit in the last line of your batch-file otherwise the CMD task does not close and your server will be filled with dead processes ... No idea what happens with other programs .

For Win2k/XP systems, and probably NT as well, after beating my head against a wall for a few days on this, I finally found a foolproof way of backgrounding processes and continuing the script.

For some strange reason I just could not seem to get backgrounding to work with either system or exec, or with the wsh.run method for that matter. I have used all three in the past with success, but it just wasn't happening this time.

If you try to use the psexec from Sysinternals on your Windows Server for background-processes that need special user-rights and get an "Access denied" oder "Wrong user or password" notice, although your username and password is right, this could help you getting around this bug.

Running a command that may never time out on a windows server inspired the following code. The PsExecute() function allows you to run a command and make it time out after a set period of time. The sleep parameter is the number of seconds the script will pause becore checking if the process is complete.

For those that don't know what usrstat is, it's a program that is the admin pack for win2k that lists users in a domain and thier last logon time. I used it as the example to show that arguments can be passed (the domain).

The one "gotcha" is that usrstat.exe must be in the system path...ie if you are at the server w/ a command window, anything you can type w/o typing in a path, works. Try it with ping, since that should be in system32 for just about everyone...

[ Editor's note: When passing multiple args in a URL like this, be sure to enclose the URL in quotes otherwise the & will be interpreted as a detachment flag and the rest of the command will be truncated. ]

The lynx browser can be used as simple way of executing a script from a remote location without waiting for it to complete:

If you're trying to run something in the background on a system that uses systemd for its init, use the systemd-run utility to start your program in the background. systemd-run will run the command in a transient unit file so that you can query its status with systemctl and view its log with journalctl.

systemd-run returns immediately, launching your application for you and keeping track of it, so you don't need to worry so much about a forgotten process running on your server. From here you can query its status with<?php$lastline = exec('systemctl status my_unit_name', $output, $exitval);?>

Note that the exec() function calls the program DIRECTLY without any intermediate shell. Compare this with the backtick operator that executes a shell which then calls the program you ask for.

This makes the most difference when you are trying to pass complex variables to the program you are trying to execute - the shell can interpret your parameters before passing them thru to the program being called - making a dog's breakfast of your input stream.

Remember: exec() calls the program DIRECTLY - the backtick (and, I THINK, the system() call) execute the program thru a shell.

* execute an external command.
* check if the execution was ok. (i.e. the return level)
* log the error output if the execution wasn't ok.
* not print the command's output in my script's output.

I saw the exec, system, shell_exec and passthru functions, and deduced that the solution was to redirect the standard error (stderr) to the standard output (stdout). It's not very clean, since it mixes stderr with stdout, and I only wanted to log the stderr. But it seems to be the only solution (suggestions are welcome).

Remember that some shell commands in *NIX needs you to set a TERM enviroment. For example:<?phpexec('top n 1 b i', $top, $error );echo nl2br(implode("\n",$top));if ($error){exec('/usr/bin/top n 1 b 2>&1', $error ); echo "Error: "; exit($error[0]);}?>This will echo "Error: TERM enviroment variable not set. " To fix it, add TERM=xterm (Or some other terminal) to the exec-statement, like this

Side-note: regarding the API comment "For practical reasons, it is currently not allowed to have .. components in the path to the executable."

It is still possible to pass the shell as the first command and a relative path to the script as the second, so this limitation/security mechanism is not much of one. "sh" can be used to run non-scripts with relative paths via something like this:

You can embed php into a batch file so that it is essentially "double-click" to run. This might be useful for script that does search and replace in numerous files or other tedious task that are too complex for batch files but don't warrant greater attention. Its really quite simple I'm sure someone has thought of it before. You can add whatever batch code you want after :START just make sure you exit before you get to */ so Windows doesn't fuss. @php %0 basically is saying "Open this file with php and run its php code". Obviously its really only a useful trick on Windows, I only really use it for update scripts on our company's servers. I suppose you could also just set Windows to open php files with php.exe but that seems like a rather stupid thing to do as you would most often want to edit php files, not run them directly. @pause is optional of course, but you may want to look at what php outputted to the command line before it exits.

Recently I had to do some "root" stuff via PHP - I could do it through cronjob based on the database, but since I was too lazy with doing that, I just wrote a shell script to create all the IMAP stuff, chown properly all the Maildirs and provision the user on the local system.

Executing that command as another user from inside of PHP was like this...

"Advantage" is that you can run in this way commands as any sudoer on your system which can be fine-tuned and pretty useful. But again - password is echoed in cleartext and option "-S" tells sudo to take password from stdin which he does of course.Major security risk - do it only if you really need to run some commands as different users (nologin users) and if you are really lazy :)

Now, my solution is a cronjob which runs every 5 mins and gets datasets from the MySQL table and does the work without exploiting any exec() from within PHP - which is the right way to do it.

It is possible to only capture the error stream (STERR). Here it goes...

(some_command par1 par2 > /dev/null) 3>&1 1>&2 2>&3

-First STDOUT is redirected to /dev/null.-By using parenthesis it is possible to gain control over STERR and STOUT again.-Then switch STERR with STOUT.

The switch is using the standard variable switch method -- 3 variables (buckets) are required to swap 2 variables with each other. (you have 2 variables and you need to switch the contents - you must bring in a 3rd temporary variable to hold the contents of one value so you can properly swap them).

If you guys start a process or e.g. a script which starts processes sub processes, look that you uncouple them from your php script. Otherwise you get the same problem as I, your php script will wait to get the feedback from the server. So it will wait until the sub processes are dead.

I know two ways to counter that, one way is to make sure the sub processes dont get linked to the parent process.

The other way is to fire and forget with php (on Unix/Linux just add "/dev/null 2>&1 &" to end of your command, but you should remember you wont get any output from the process.)

Hope that will help some of you, I had a while until I came on this idea.

Note that on Linux/UNIX/etc, both the command and any parameters you send is visible to anyone with access to ps.

For example, take some php code that calls an external program, and sends a sort of password as a parameter.

<?phpexec("/usr/bin/secureprogram password");?>

The entire string (actually probably something like "secureprogram password") will be visible to any user that executes ps -A -F. If you are going to be doing a lot of external calling, or any of it needs to be somewhat secure, you are probably better off writing a php extension.