shell_exec

(PHP 4, PHP 5)

shell_exec -- Execute command via shell and return the complete output as a string

说明

string shell_exec ( string cmd )

This function is identical to the backtick operator.

参数

cmd

The command that will be executed.

返回值

The output from the executed command.

范例

例子 1. A shell_exec() example

<?php
$output
= shell_exec('ls -lart');
echo
"<pre>$output</pre>";
?>

注释

注: 本函数在安全模式下被禁用。


add a note add a note User Contributed Notes
arturm at union dot com dot pl
30-Oct-2006 06:28
If someone has problems with IIS6 and CGI error message "The specified CGI application misbehaved by not returning a complete set of HTTP headers.", simply make sure that headers are already sent:
echo "<head>";
flush();
$result = shell_exec('C:\util\myprog.exe');
kees dot schepers at infolook dot nl
12-Oct-2006 08:27
If you are using a Windows server with IIS, and you try to execture a batch file with shell_exec() function, or his related functions you should do it like this:

<?
shell_exec
("C:\\path\\to\\cmd.exe /c C:\\batchfile.cmd");
?>

Note the parameter /c which says "Carries out the ommand specified by string and then terminates"

If you don't add the parameter /c the batch file will not be executed, only the cmd.exe file will.

As, also mentiod in these commants, put your cmd.exe file in your php folder, and your windows folder for security reasons.
Paul Cook
17-Sep-2006 02:00
The technique mentioned by Nathan De Hert below is rather insecure -- you should never leave a password lying around in a file readable by the apache user.

If you need this sort of functionality on *nix systems, have a look at the /etc/sudo file (edited with the command 'visudo'). The tag NOPASSWD allows specified commands to be run as root by another user, without needing to specify a password. It's a little extra configuration, but much more secure.
ruan at nospam dot tillcor dot com
25-Aug-2006 11:31
When following Kenneth's method for executing root scripts via the nanoweb server mentioned on this page you would most likely need to be able to run a text-mode browser like lynx and pass the php script to it (works great).

After struggling for a while (lynx kept asking me to download the file instead of executing it), I realised that I had to install php-cgi additionally and modify the nanoweb config file  to use that php interpreter instead of /usr/bin/php. (On Debian this is the CLI version).

On Ubuntu 6.06:

apt-get install php5-cgi

After editing /etc/nanoweb/nanoweb.conf and a quick restart of the web server, lynx and links will execute your PHP scripts properly.

Hope this helps somebody else out there :)

Ruan Fourie
nathandehert at no spam gmail dot com
07-Aug-2006 04:29
If you want to execute shell commands as root theres another workaround.

<?php
shell_exec
('sudo -u root -S command_goes_here < /home/$User/dir/dir/dir/passfile');
?>

It will readout the file 'passfile' that you've hidden under quite some dirs (to make it a bit less insecure) and use the content as password to login as root.

Note that storing your root password is far from secure but it's an easy way to execute commands under root in controlled environments.

Nathan De Hert
Kishan
05-Aug-2006 01:27
If you are on windows and has Cygwin, You can execute all your Cygwin binaries using shell_exec() as follows:

<?
$result
= shell_exec("C:\cygwin\bin\bash.exe --login  -c '/cygdrive/c/cygwin/bin/convert.exe --version'");
print(
$result);
?>

The key is the "--login"  option which appends all the required common cygwin binary and library paths to $PATH. Without this option some of the cygwin binaries that links to other libraries ( Like ImageMagick binaries which links to X11 ) will not work and you may see errors like "cygX11-6.dll not found, Could not start convert.exe"
doo_mangle_fus at by_mangle_u dizzot net
03-Aug-2006 03:00
If you're on a host that provides neither shell access nor a way to unzip uploaded archives, you can use PHP to call the unzip utility with shell_exec() (provided they're not also running in safe mode). Just make sure that PHP has write permission to the destination directory, or it won't work.

Here's an example script that accomplishes this, which you're free to use if you so chose:

<?php
$passwd
= 'censored';
$filename = 'archive.zip';
$options = '-o'//Overwrite existing files by default; this is mostly to suppress confirmations
$destDir = '';

if (isset (
$_POST['password']))  {
   if (
$_POST['password'] == $passwd)  {
       if (isset (
$_POST['filename']))  { $filename = escapeshellarg ($_POST['filename']); }
       if (isset (
$_POST['updateExisting']))  { $options .= "u"; }  //use with care, since a timezone mismatch may occur; see man unzip
      
if (isset ($_POST['destDir']))  { $destDir = ' -d '. escapeshellarg ($_POST['destDir']); }
      
       echo
"<pre>";
       echo
shell_exec ("unzip $options {$filename}{$destDir}");
       echo
"</pre>";
   }
   else  {
      
outputPage ("Your password didn't check out, mon. Better try it again, eh?");
   }
}
else  {
outputPage(); }

function
outputPage ($errorMessage = '')  {
   echo <<<HTML
        <html><head><title>Unzip password verification</title>
           <style type="text/css">
               td.left 
{ text-align: right; }
               td.right
{ text-align: left; }
              
               div 
{ color: red; border: 1px solid gray; padding: 4px; }
           </style>
       </head>
       <body>
HTML;

   if (!empty (
$errorMessage))  { echo "\n<div>$errorMessage</div>\n"; }
  
   echo <<<HTMLL
        <h1>Super Duper File Unzipper</h1>
       <form name="zipform" method="post" action="unzipper.php">
           <table>
               <tr>
                   <td class="left">Filename:</td>
                   <td class="right"><input type="text" name="filename" size="50" maxlength="255" /></td>
               </tr><tr>
                   <td class="left">Destination Directory:</td>
                   <td class="right"><input type="text" name="destdir" size="50" maxlength="1000" /></td>
               </tr><tr>
                   <td class="left">Password:</td>
                   <td class="right"><input type="password" name="password" size="15" maxlength="30" /></td>
               <tr>
                   <td colspan="2"><input type="checkbox" name="updateExisting" />Update existing files</td>
               </tr><tr>
                   <td class="right"><input type="reset" value="Reset" /></td>
                   <td class="left"><input type="submit" value="Unzip it!" /></td>
               </tr>
           </table>
          
       </form>
       </body>
       </html>
HTMLL;
}
?>
rustleb at hotmail dot com
05-Jun-2006 04:45
For capturing stdout and stderr, when you don't care about the intermediate files, I've had better results with . . .
<?php
function cmd_exec($cmd, &$stdout, &$stderr)
{
  
$outfile = tempnam(".", "cmd");
  
$errfile = tempnam(".", "cmd");
  
$descriptorspec = array(
      
0 => array("pipe", "r"),
      
1 => array("file", $outfile, "w"),
      
2 => array("file", $errfile, "w")
   );
  
$proc = proc_open($cmd, $descriptorspec, $pipes);
  
   if (!
is_resource($proc)) return 255;

  
fclose($pipes[0]);    //Don't really want to give any input

  
$exit = proc_close($proc);
  
$stdout = file($outfile);
  
$stderr = file($errfile);

  
unlink($outfile);
  
unlink($errfile);
   return
$exit;
}
?>

This isn't much different than a redirection, except it takes care of the temp files for you (you may need to change the directory from ".") and it blocks automatically due to the proc_close call.  This mimics the shell_exec behavior, plus gets you stderr.
squeegee
05-May-2006 01:36
Each time you call shell_exec, it operates in a completely new shell. So if you need to do different multiple things in it based on whatever criteria, assemble your command ahead of time:

instead of

<?php
shell_exec
("cd $path_to_dir");
shell_exec("ls -l");
?>

which, as you noted, won't work, do

<?php
$cmd
= "cd $path_to_dir; ";
if(
$a == true)$cmd .= "ls -l";
else
$cmd .= "du -h";
$result = shell_exec($cmd);
?>
notmespammers-iain at iaindooley dot com
19-Feb-2006 07:38
beware!

shell_exec('cd /path/to/dir');
shell_exec('ls -l');

will not give a listing of /path/to/dir!! use chdir() if you need to change directories, or group your commands with && (not always convenient/possible)

cheers

iain
rigsbr at yahoo dot com dot br
17-Feb-2006 10:24
If you need to execute a command without permission and could not execute it by ssh or install any extension, there is a way in Apache 1.3.x and PHP 4.
Create a file on cgi-bin directory, like this:

#!/usr/bin/php
<?
 
echo shell_exec('whoami');
?>

Don't forget to set the file you created the permission to execute it. Hence, call it from browser and you will se that this script will be executed by the shell user and not the user nobody (apache default user if running a PHP script).
andy25it at hotmail dot it
03-Jan-2006 01:06
As a webmaster i often deal with other servers with respect to the one that hosts my own site.
I actually had to face the following problem: some web pages depend directly from other webservers for example including a IMG SRC tag pointing to a remote image; but what if the remote server is temporary down? The download of the page remains in an incomplete state. It'd be better an error message for sure ! But how can i know whether the remote server is up or down? PING IT  is the answer..but how can i use a shell system function that outputs only text into some PHP scripting?..here the solution:

<?php

/*
the host whose service status has to be checked out
*/
$host_to_ping = "www.somehost.net" ;

/*
I ping twice the host (a higher number of ping would only result the execute script time to be MUCH high).
The result of the output ping command is stored into a variable. This can be done beacuse of the properties and features of the shell_exec() function, see above to know more.
*/
$outputShell = shell_exec("ping -c2 -w2 $host_to_ping") ;

/*
Now the only thing i have to do is to look up the '0 received' string into the output to know whether the server is down or up.
*/

if(strpos($outputShell, '0 received')) {
  
  
#SERVER is DOWN so i include an error message

}
else {

  
#SERVER is UP so i include the normal code that is meant to be included by default

}

?>

I used the shell_exec() function for 2 reasons:

1) the system() function is disabled in my webserver by the hosting company for security reasons

2) the shell_exec() function returns a string containing the output of the shell command.

Regards to the community. Hope to have given a hand.

Andrea from Italy
Ashraf Kaabi
20-Dec-2005 02:06
I've write a Full Class for Run in Background, Kill PID , check if is Running

<?php
/**
 * @author    Ashraf M Kaabi
 * @name      Advance Linux Exec
 */
class exec {
  
/**
     * Run Application in background
     *
     * @param    unknown_type $Command
     * @param    unknown_type $Priority
     * @return    PID
     */
  
function background($Command, $Priority = 0){
       if(
$Priority)
          
$PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
       else
          
$PID = shell_exec("nohup $Command > /dev/null & echo $!");
       return(
$PID);
   }
  
/**
   * Check if the Application running !
   *
   * @param    unknown_type $PID
   * @return    boolen
   */
  
function is_running($PID){
      
exec("ps $PID", $ProcessState);
       return(
count($ProcessState) >= 2);
   }
  
/**
   * Kill Application PID
   *
   * @param  unknown_type $PID
   * @return boolen
   */
  
function kill($PID){
       if(
exec::is_running($PID)){
          
exec("kill -KILL $PID");
           return
true;
       }else return
false;
   }
};
?>
php [AT] jsomers [DOT] be
27-Sep-2005 09:00
<?php

/**
 * PHP Kill Process
 *
 * Sometimes, it can happen a script keeps running when it shouldn't, and it
 * won't stop after we close the browser, or shutdown the computer. Because it's
 * not always easy to use SSH there's a workaround.
 *
 * @author      Jensen Somers <php@jsomers.be>
 * @version    1.0
 */
 
class KillAllProcesses {
  
/**
     * Construct the class
     */
  
function killallprocesses() {
      
$this->listItems();
   }
  
  
/**
     * List all the items
     */
  
function listItems() {
      
/*
         * PS  Unix command to report process status
         * -x  Select processes without controlling ttys
         *
         * Output will look like:
         *      16479 pts/13  S      0:00 -bash
         *      21944 pts/13  R      0:00 ps -x
         *
         */
      
$output shell_exec('ps -x');
      
      
$this->output($output);
      
      
// Put each individual line into an array
      
$array  explode("\n", $output);
      
      
$this->doKill($array);
   }
  
  
/**
     * Print the process list
     * @param  string  $output
     */
  
function output($output) {
       print 
"<pre>".$output."</pre>";
   }
  
  
/**
     * Kill all the processes
     * It should be possible to filter in this, but I won't do it now.
     * @param  array  $array
     */
  
function doKill($array) {
      
/*
         * Because the first line of our $output will look like
         *        PID TTY      STAT  TIME COMMAND
         * we'll skip this one.
         */
      
for ($i = 1; $i < count($array); $i++) {
          
$id substr($array[$i], 0, strpos($array[$i], ' ?'));
          
shell_exec('kill '.$id);
       }
   }
}

new
KillAllProcesses();

?>

It's not the very best solution, but I've used it a couple of times when I needed to do it quick without to much trouble.
Make not I kill all the processes, on my server px -x will only return like 4 times /sbin/apache and it's pretty safe to kill them without any trouble.
concept at conceptonline dot hu
20-Sep-2005 05:02
Interestingly, if you execute a script which is not in your path (or you have made a typo, or if the script does no exist at all), you will get no return value. The error will be logged into the error_log of your webserver.

Someone could add a note how this can be (if it could be) overriden, as the standard behaviour is not really fool-proof.
ludvig dot ericson at gmail dot com
02-Sep-2005 02:50
(if you have any other way of doing this PLEASE send me a mail)
(The following note is interesting to *NIX administrators ONLY)
Jailing a PHP CLI session is not the easiest thing to do.

PHP has a gigantic list of dependencies, you can check it by
ldd `which php`
Each of these .so files (shared libraries) can have dependencies, and can depend on each other, making the list much bigger.
However, there are tools out there to copy all dependencies into a jailed directory, you just have to search for them - and I had no luck.

What I did was just to run these few commands:
su
mkdir /jailpath && mkdir /jailpath/lib
cp /lib/*.so* /jailpath/lib/
mkdir /jailpath/usr && mkdir /jailpath/usr/bin && mkdir /jailpath/usr/lib
cp /usr/lib/*.so* /jailpath/usr/lib
cp `which php` /jailpath/usr/bin
chmod -R 0755 /jailpath && chown -R root:root /jailpath && chmod 0000 /jailpath

Do note that this copies _all_ of your shared objects. There is one or two more libraries you have top copy, but chroot will tell you about which one it is.

Hope this helped somehow.
jesuse dot gonzalez at venalum dot com dot ve
15-Jul-2005 07:34
Here is an example of how you can execute a command in background an get the Process ID created by *NIX, for future reference or monitoring.

<?php
  
//Run linux command in background and return the PID created by the OS
  
function run_in_background($Command, $Priority = 0)
   {
       if(
$Priority)
          
$PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
       else
          
$PID = shell_exec("nohup $Command > /dev/null & echo $!");
       return(
$PID);
   }
?>

There is also a trick which  I use to track if the background task is running using the returned PID

<?php
  
//Verifies if a process is running in linux
  
function is_process_running($PID)
   {
      
exec("ps $PID", $ProcessState);
       return(
count($ProcessState) >= 2);
   }
?>

I commonly use both functions in combination to batch copy big mysql tables in background and wait for the copy process to finish sending chunks to the client browser in the following way:

<?php
   $CopyTaskPid
= run_in_background("mysql --user=backup_user --password=backup_user_password --execute='INSERT INTO `backup-db`.`table` SELECT * FROM `online-db`.`table`'", "+20");
   while(
is_process_running($CopyTaskPid))
   {
       echo
".";
      
ob_flush(); flush();
      
sleep(2);
   }
?>
joanacosta at prodigy dot net dot mx
25-May-2005 08:25
Here is another good example of how to Create a File with some variables already defined by user, and creating a file with them. of course using shell_exec

<?php
$generatefile
= shell_exec("echo '$thisFOLIO','$thisREPORTO','$thisRESOLVIO','$thisVISTOB'  > datosmanda.txt");
echo
"<pre>$generatefile</pre>";
?>

Php Is Great.... cheers
dk at brightbyte dot de
14-May-2005 04:25
her's a function that is similar to shell_exec but captures both stdout and stderr. It's much more complicated than using 2>&1, but it's independent of the shell and should work on windows, too. It uses proc_open with stream_select and non-blocking streams to read stdout and stderr concurrently. It is not guarantied that the lines appear in the correct order or that they are not intermingeled - but it did not happened when I tested it. So, here goes:

<?php
  
function runExternal($cmd,&$code) {
      
$descriptorspec = array(
          
0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
          
1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
          
2 => array("pipe", "w") // stderr is a file to write to
      
);
      
      
$pipes= array();
      
$process = proc_open($cmd, $descriptorspec, $pipes);
      
      
$output= "";
      
       if (!
is_resource($process)) return false;
      
      
#close child's input imidiately
      
fclose($pipes[0]);
      
      
stream_set_blocking($pipes[1],false);
      
stream_set_blocking($pipes[2],false);
      
      
$todo= array($pipes[1],$pipes[2]);
      
       while(
true ) {
          
$read= array();
           if( !
feof($pipes[1]) ) $read[]= $pipes[1];
           if( !
feof($pipes[2]) ) $read[]= $pipes[2];
          
           if (!
$read) break;
          
          
$ready= stream_select($read, $write=NULL, $ex= NULL, 2);
          
           if (
$ready === false) {
               break;
#should never happen - something died
          
}
          
           foreach (
$read as $r) {
              
$s= fread($r,1024);
              
$output.= $s;
           }
       }
      
      
fclose($pipes[1]);
      
fclose($pipes[2]);
      
      
$code= proc_close($process);
      
       return
$output;
   }
?>

here is how to use it:

<?php
$result
= runExternal("ls -l some-file.txt",$code);

print
"<pre>";
print
$result;
print
"</pre>\n";

print
"<b>code: $code</b>\n";
?>

enjoy :-)
phillipberry at NOSPAM dot blisswebhosting dot com
11-Apr-2005 04:13
I found something odd.

If you run exec then straight after shell_exec the shell_exec will simply not run and will return NULL.

To get it to work i put a sleep(5) after the exec and now shell_exec works fine.
Kenneth
10-Mar-2005 01:19
Sometimes it's needed to be able to execute shell commands as root using PHP. For instance, restarting named after adding or changing zones, or adding new alliases for sendmail.

My approach is to run a server called Nanoweb, available from  http://nanoweb.si.kz/. It's a webserver written in PHP, and needs only the pcntl extension extra to operate. Nanoweb is configured to only listen for connections on localhost, port 81 for example. From my normal PHP scripts running inside Apache I simply call scripts in Nanoweb to get the messy 'root' tasks done. Much more secure and safer.

Hope this helps
04-Jan-2005 01:10
Be careful as to how you elevate privileges to your php script.  It's a good idea to use caution and planing.  It is easy to open up huge security holes.  Here are a couple of helpful hints I've gathered from experimentation and Unix documentation.

Things to think about:

1. If you are running php as an Apache module in Unix then every system command you run is run as user apache.  This just makes sense.. Unix won't allow privileges to be elevated in this manner.  If you need to run a system command with elevated privileges think through the problem carefully!

2. You are absolutely insane if you decide to run apache as root.  You may as well kick yourself in the face.  There is always a better way to do it.

3. If you decide to use a SUID it is best not to SUID a script.  SUID is disabled for scripts on many flavors of Unix.  SUID scripts open up security holes, so you don't always want to go this route even if it is an option.  Write a simple binary and elevate the privileges of the binary as a SUID.  In my own opinion it is a horrible idea to pass a system command through a SUID-- ie have the SUID accept the name of a command as a parameter.  You may as well run Apache as root!
snoj-wwwposter at latitude dot li
30-Sep-2004 05:53
if the script you want to run from shell_exec needs more permissions than the webserver has (for example script needs root priviliges, do:

# chown root:root
# chmod 4711!

of course, replace root:root with the user that the script needs to run as and tweek the chmod for your security policy.

!! be careful about what the script does!  remember it has root privilige!
James McCormack
06-Aug-2004 04:50
I had a perl program which ran fine from command line but not using shell_exec(), exec() or system() - nothing was being returned. I was using the full path and permissions were set correctly.

It turned out the perl program was using more memory than my PHP.INI file was set to allow. Increasing "memory_limit" solved the problem.
leaetherstrip at inbox dot ru
08-Jul-2004 05:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use 'cacls' command-line utility to do this.

For example:

cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F

gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
vsuarez at vorealis dot com
01-Jul-2004 09:34
Got the error "Unable to execute..." when trying to run an external program with shell_exec under Windows XP, IIS 5, php 4.3.7  Solved by giving the IIS user (IUSR_...) execution privileges on the system file %systemroot%\system32\cmd.exe  This should be used carefully because may represent a server's security hole.
dj-bj at gmx dot net
17-Mar-2004 09:22
shell_exec passes the result to a variable only if the result of the command is true.

When the result is false the generated page contains the error string in clear text at the position the result was fetched (which can differ from reload to reload).

If you would like to recieve also the error messages append 2>&1 to the end of the command you are executing.
However, the result is also passed to the page directly.

To avoid page destruction you should not fetch the result in your script.
By appending >nul to the shell command you can hide any output.
Hope this helps.
Martin Rampersad
11-Jan-2004 05:13
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage.  Shell scripts that start with #!/usr/bin/bash return their output properly.

A solution is to force a clean environment.  PHP CLI no longer had the CGI environment variables to choke on.

<?php

// Binary garbage.
$ExhibitA = shell_exec('/home/www/myscript');

// Perfect.
$ExhibitB = shell_exec('env -i /home/www/myscript');

?>

-- start /home/www/myscript
#!/usr/local/bin/phpcli
<?php

echo("Output.\n");

?>
-- end /home/www/myscript
spagmoid at yahoo dot NOSPAMcom
18-Dec-2003 06:52
Note that whatever you run with this function seems to use PHP memory, so it will die if it exceeds the limit (usually 8 megs)  To do database dumps or other memory-hogging operations use something like system() instead.
jessop <AT> bigfoot <DOT> com
04-Dec-2003 04:19
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
ericphp at shepard dot com
23-Nov-2003 06:45
I had major problems getting sell_exec() to work from PHP. It was working fine via the Telnet command line.

Turns out (for me anyway) it was a pathing problem. I'm set up on a VPS FreeBSD server the does not (technically) have root access.

PHP needs to reference the FULL PATH to the app it's calling. But it gets more tricky than that. There may be more than one full path on a server. For instance, on mine there is:

>find ~/ -name mysqldump (VPS non-root search method)

/usr/local/bin/mysqldump
/usr/home/myusername/usr/local/bin/mysqldump
/usr/home/myusername/usr/local/mysql-3.23.41/bin/mysqldump
/usr/home/myusername/usr/local/mysql-3.23.43/bin/mysqldump

Turns out (after 5 hours of hair pulling fun) that /usr/home/myusername/usr/local/mysql-3.23.43/bin/mysqldump was the winner.

The same applies to using cURL and PHP via Cron. /usr/home/myusername/usr/local/curl-7.10.5/bin/curl  works for me there.

And tar wouldn't work until I dug up PHPTAR /usr/home/myusername/usr/local/bin/phptar. Never new that existed ...

Good luck.
moneyboi at fuckwindows dot com
17-Jul-2003 09:46
shell_exec("yourscript.sh") is great for opening shell scripts.
eremi at eremi dot net
10-Jun-2003 01:29
To output the command has it should be, you can do the str_replace trick above, or you can put the output in a <pre> tag.

Example:
<?php
  $output
= shell_exec("[command]");
  echo
"<pre>$output</pre>";
?>
Ben
05-Jun-2003 01:01
When running subprocesses via shell_exec (and maybe others) from Apache/mod_php4, Apache's environment variables don't seem to be passed on to the subprocess environment unless you specifically force them by using putenv something like this:

$remaddr = getenv("REMOTE_ADDR");
putenv("REMOTE_ADDR=$remaddr");
shell_exec("/path/to/subprocess");
dan at mathjunkies.com
16-Apr-2003 12:02
Just a note for anybody who's box is involuntarily running in safemode (i.e. you buy space on a server), or just not working right.  Shell commands won't work.  You can, however, use PHPs FTP functions to FTP in.  I was copying files and making directories, but I assume there might be a way to do something more complex.
mcbeth at broggs dot org
15-Apr-2003 05:18
As far as error checking on the last example.  Several of the shells have the && operator, so you just string your commands together using it instead of ; If at any time any of the programs fail, you will return without running the rest
ron dot petty at unigeek dot com
22-Mar-2003 03:40
Here is an example on how to install software using php

shell_exec("cd /usr/local/src/; gunzip program.tar.gz; tar xvf program.tar; cd program; ./configure; make; make install);

Now depending if your root or not some commands like "make install" may fail.  This doesn't do any error checking, the reason for that is I do not know how to cd to a directory and then execute another command unless they are in the same shell. 

So basically, take what you type on the command line and string them together.
bruce at accumatics dot com
02-Feb-2003 01:24
If you're not getting any output from echo shellexec( "count.pl" ) [for instance], at least try "./count.pl" before bothering with the full path.
flame
30-Jan-2003 10:21
add  '2>&1' to the end of your shell command to have STDERR returned as well as STDOUT.

$shell_return = shell_exec($shell_command." 2>&1");
ryon -at- ryon labaw -dot- com
17-Jan-2003 04:47
Note: You cant used shell_exec() when safemode = on (its disabled), instead use
exec() and copy the needed program into the /nonexec directory (by default, set in php.ini).
dj-bj at gmx dot net
17-Dec-2002 10:27
Running PHP 4.2.3 on Windows 2000 Server shell_exec works fine and passes its output to the variable when the result of the executed command is true.
However, if the command fails and the DOS-shell returns an error the result is no longer availiable in the variable but is passed directly to the page.
yaacov at pleasedontspamme dot spam
30-Oct-2002 02:46
If you're running scripts or commands and can't figure out what's not working, check to make sure that you're not using an alias in place of a command. PHP (quite reasonably) doesn't seem to recognise aliases.
php at chris-decker dot com
25-Jun-2002 02:12
I have found it easiest to use the following code to execute a shell command and return all of it's output (not just the last line) to the user as if he/she were sitting at the terminal:

$output = shell_exec("$command");
echo(nl2br($output));
matt_smith&uconn_edu
19-Jun-2002 12:51
Re: executing scripts that work on command line, but not from PHP system() calls -- Make sure you include the full path to the executable.
tonysb at gmx dot net
31-Mar-2002 04:57
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:

<?
$mstrng
= shell_exec('yourcgiscript.cgi');
$mstrng = ereg_replace( "Content-type: text/html", "", $mstrng );
echo
$mstrng;
?>

This works fine for me as a substitute for SSI or the virtual() func.

Anton Babadjanov
http://www.vbcn.com.ar