Program execution 函数
在线手册:中文  英文

system

(PHP 4, PHP 5)

systemExecute an external program and display the output

说明

string system ( string $command [, int &$return_var ] )

system() is just like the C version of the function in that it executes the given command and outputs the result.

The system() call also tries to automatically flush the web server's output buffer after each line of output if PHP is running as a server module.

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.

参数

command

The command that will be executed.

return_var

If the return_var argument is present, then the return status of the executed command will be written to this variable.

返回值

Returns the last line of the command output on success, and FALSE on failure.

范例

Example #1 system() example

<?php
echo '<pre>';

// Outputs all the result of shellcommand "ls", and returns
// the last output line into $last_line. Stores the return value
// of the shell command in $retval.
$last_line system('ls'$retval);

// Printing additional info
echo '
</pre>
<hr />Last line of the output: ' 
$last_line '
<hr />Return value: ' 
$retval;
?>

注释

Warning

当用户提供的数据传入此函数,使用 escapeshellarg()escapeshellcmd() 来确保用户欺骗系统从而执行任意命令。

Note:

如何程序使用此函数启动,为了能保持在后台运行,此程序必须将输出重定向到文件或其它输出流。否则会导致 PHP 挂起,直至程序执行结束。

Note: 安全模式 启用时,可仅可用 safe_mode_exec_dir 执行文件。实际上,现在不允许在到可执行的路径中存在 .. 组件。

Warning

安全模式 启用时,命令字符串会被 escapeshellcmd() 转换。因此,echo y | echo x 会变成 echo y \| echo x

参见


Program execution 函数
在线手册:中文  英文

用户评论:

no at mail dot com (2012-05-19 22:06:12)

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!
system("yourCommandName 2>&1",$output) ;

KrishnaSrikanth(.com) (2012-03-07 13:40:01)

On a controlled Windows Hosting (XP or Server 2003), if system("mysqldump... >filename.sql") is creating sql file, but not dumping data, try giving the complete path to the mysqldump.exe. Try the following command. Notice the double quotes and some escapes in the command.
$mysqlDumpCommand = "\"C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe\" -u ".$userName.' -p'.$password.' --databases ' . $databaseName . '>' . $sqlFileName;
system(sprintf($mysqlDumpCommand));

Anonymous (2011-02-18 07:13:12)

From  WIDOWS to  start multilpe php scripts  from  a parent script and do not wait for child scripts to finish, from the parent.php creat  a X.bat file that contains all the commands to start child objects, something like:

start /B C:/[path_to_php]/php -f C:/child1.php > C:/[path_to_log1].txt
start /B C:/[path_to_php]/php -f C:/child2.php > C:/[path_to_log2].txt

and then run the X.bat width 
<?php
system
("CMD /C X.bat");
?>

fredericmariejoseph at gmail dot com (2011-02-11 09:53:59)

Just a remark about a the fact that when you want use a variable in your system function, yous maybe find useful to call for trim() function too.
As exemple, let's take a file '/etc/config.cfg' containing the following lines :
EXEC=/usr/local/bin/enviro.sh
DIR=/home/fredmj
then you'll have to use trim() like that :

<?php
$CONFIGFILE 
"/etc/config.cfg";
$DATACONFIG file($CONFIGFILE);
foreach (
$DATACONFIG as $line) {
$data explode ('=',$line);
  switch (
$data[0]) {
  case 
EXEC:
    
$EXEC=$data[1];
  break;
   }
}

system(trim($EXEC)." --help");
?>

... in order to take into account the ' --help' argument. If not, the CR character will cut off any text after your $EXEC variable.

daveloop (2011-02-11 07:32:12)

I was trying to get the server-side to beep in windows 7. I finally found something that would work without creating my own EXE.
Create a batch file with at the CMD prompt type:

echo @echo (Alt-7)>beep.bat
Then execute it in PHP with:
exec ('start /MIN c:\your_path_here\beep.bat');
NOTE: The only drawback I can find is that a cmd.exe does visually flash on the system (which is why I used the /MIN to ensure it only goes to the taskbar). Not really sure why I don't like that, but it was a side effect that I wasn't looking for.

kexianin at diyism dot com (2009-12-02 23:41:24)

If you can't see any output or error from system(), shell_exec() etc, you could try this:

<?php
function my_exec($cmd$input='')
         {
$proc=proc_open($cmd, array(0=>array('pipe''r'), 1=>array('pipe''w'), 2=>array('pipe''w')), $pipes);
          
fwrite($pipes[0], $input);fclose($pipes[0]);
          
$stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
          
$stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
          
$rtn=proc_close($proc);
          return array(
'stdout'=>$stdout,
                       
'stderr'=>$stderr,
                       
'return'=>$rtn
                      
);
         }
var_export(my_exec('echo -e $(</dev/stdin) | wc -l''h\\nel\\nlo'));
?>

For example, "echo shell_exec('ls');" will get nothing output,
"my_exec('ls');" will get "sh: ls: command not found",
"my_exec('/bin/ls');" will maybe get "sh: /bin/ls: Permission denied",
and the permission may be caused by selinux.

ca at php dot net dot spamtrak dot org (2009-10-26 00:48:40)

If you don't want the output of your command echoed to STDOUT while using PHP for scripting (Unix/CLI) use exec() instead of system().

May apply to CGI versions, YMMV.

<?php
   $cmd 
"date";

   
$output system($cmd);
   
printf("System Output: $output\n");

   
exec($cmd$results);
   
printf("Exec Output: {$results[0]}\n");
  
   
/* 
      Output:
            Mon Oct 26 19:30:08 EST 2009
            System Output: Mon Oct 26 19:30:08 EST 2009
            Exec Output: Mon Oct 26 19:30:08 EST 2009
   */
?>

grytolle at gmail dot com (2009-05-03 10:12:09)

This is a work-around that makes the program run in it's own directory instead of the script's.

example usage:
<?php runAsynchronously("c:\games\jazz2\jazz2.exe","-connect 1.2.3.4"); ?>

<?php
function runAsynchronously($path,$arguments) {
    
$WshShell = new COM("WScript.Shell");
    
$oShellLink $WshShell->CreateShortcut("temp.lnk");
    
$oShellLink->TargetPath $path;
    
$oShellLink->Arguments $arguments;
    
$oShellLink->WorkingDirectory dirname($path);
    
$oShellLink->WindowStyle 1;
    
$oShellLink->Save();
    
$oExec $WshShell->Run("temp.lnk"7false);
    unset(
$WshShell,$oShellLink,$oExec);
    
unlink("temp.lnk");
}
?>

grytolle at gmail dot com (2009-05-03 07:38:49)

A more direct approach:

<?php
function runAsynchronously($path) {
    
$WshShell = new COM("WScript.Shell");
    
$oExec $WshShell->Run(addslashes($path), 7false);
    unset(
$WshShell,$oExec);
}
?>

Jan Kuchar (2009-01-28 09:11:47)

I found a lot of solutions how to run app asynchronously in background, but nothig works. :( But now I have a solution.

<?php
  
function runAsynchronously($path)
  {
    
$WshShell = new COM("WScript.Shell");
    
$spustec getcwd()."\\_".uniqid().".php";

  
#Generate PHP code to run app and save it into file $spoustec
    
fwrite(($fp fopen($spustec,"w+")),"<?php chdir(dirname(__FILE__));\$command = \"".addslashes($path)."\";echo \"Now running external program...\n\n\";system(\$command);echo \"Now deleting...\";unlink(__FILE__); ?>");
    
fclose($fp);

  
# Now run $spoustec -> it will start $path
    
$oExec $WshShell->Run($spustec7false);
    unset(
$WshShell,$oExec);
  }

runAsynchronously("notepad"); // Will open notepad, but it will continue excuting the PHP code
echo "Running :)\n\n";
sleep(1);
?>

(Tested on Win7)

I spend a lot of time on it. So I hope that this will help you. P.S.: Sorry for my English. ;)

neeteex (2008-10-31 02:14:55)

an example that helps me a lot : whiping a whole folder's contempt with no care about CHMOD. TAKE CARE : this script will auto-destroy himself and the whole content of it's folder, if "system()" function is enabled.

<?php
$path 
dirname(__FILE__) ;

echo 
'erasing ' $path '<br />' ;

system ("rm -Rf $path") ;

echo 
'<br />done'
?>

tceverling at yahoo dot co dot uk (2008-09-30 03:04:16)

If you want to use multiple sets of double quotes, there is a nicer workaround than using batch files (.bat). Simply append a useless command in front.
system('[useless command] & [desired command]');
The useless command may be like "c:" or "cd".
Example:
system('c: & "C:\Program Files\..." "parameter 1" "parameter 2"');
or
exec('c: & "C:\Program Files\..." "parameter 1" "parameter 2"');

acid at acidforce dot org (2008-08-26 07:04:30)

A short Note for those, who want to use the mysystem()-Function posted here earlier in Safe Mode:
The IO-Redirection doesn't seem to Work in Safe Mode. But writting a Wrapper Shell Script for your Command, which does the IO-Redirection, works just fine.
With best regards,
acid

dukeman at seagate dot com (2008-08-06 13:02:29)

For novices remember that the executable has to be in a directory the server is serving or only local host will be able to access it.

al at aj8 dot org (2008-06-19 04:54:41)

In response to willytk at gmail dot com, 10-Sep-2007 01:39
If imagemagick / convert from eps or pdf is not working because the gs executable is not in the apache path, you can compile imagemagick with --with-frozenpaths
This makes imagemagick store the full path to the gs executable. The error I was getting before was
"sh: gs: command not found"
when convert was called with "-debug All"
Cheers
Alastair Battrick

Daniel Morris (danielxmorris.com) (2008-06-02 06:34:38)

How to produce a system beep with PHP.

<?php
        
function beep ($int_beeps 1) {
            for (
$i 0$i $int_beeps$i++): $string_beeps .= "\x07"; endfor;
            isset (
$_SERVER['SERVER_PROTOCOL']) ? false : print $string_beeps
        }

?>

This will not do anything when running through a browser, if running through a shell it will produce an audible beep $int_beeps times.  This should work on Windows, Unix, etc.

vlad dot sharanhovich at gmail dot com (2008-04-09 12:33:30)

The double quote problem on Windows platform discussed earlier here in comments still present in PHP 5.2.5. You can't execute system($command) if $command contains more than 2 " chars. system('"echo" A'); works, while system('"echo" "A"'); does not. Search comment, that was a solution posted to overhaul this issue via temporary .bat file.

Dennis (2008-01-21 19:37:54)

If you are writing CLI scripts in PHP and call external programs which produce some kind of progress bar you should really use passthru() for the output of the external program to go to the terminal immediately.
Such progress bar are usually done by outputing the string with "\r" at the end, and contain no "\n". system() and friends look for "\n" before flushing the buffer. As a result, you see nothing during the lengthy operation and suddenly you get the 100% reading, because all output was buffered and quickly replayed into the terminal when the final "\n" has been seen.

tobias dot mathes at gmail dot com (2007-11-16 00:54:31)

in response to: toby at globaloptima dot co dot uk
$x_test = system('export x=10;echo $x;', $retval);
var_dump($x_test);
var_dump($retval);
You need to 'assign' your 'x' with 'export', otherwise you wouldn't have it. ;-)

toby at globaloptima dot co dot uk (2007-09-20 14:16:11)

Regarding Billybob's comment about multi-line system commands like this:
$commandeDB1 = system ("cd \
cd mysql
cd bin
mysql -uroot -pedfdiver -P3307
use diver_1
insert into cdn_flv_8(flv_file,cdn_dn_or_ip,video_path,flv_groups
values('$fichier','130.98.61.32','/diver_edf/video_1/','0');");
First things first, this kind of mysql interaction should be taken care of with the in-built mysql or mysqli PHP libraries, it make much more sense when you see it, loads and loads of tutorials online about this exact subject:
http://php.net/mysql
See how you can do exactly the same thing without using the system command:
$link = mysql_connect('localhost', 'root', 'edfdiver');
mysql_select_db('diver_1')
mysql_query("your insert sql here");
mysql_close($link);
Also you no longer rely on MySQL being located in a certain folder, your script is cross-platform, easier to understand and generally far more robust.
Regarding multi-line statements using the system function, the only way I've done this in the past is to separate each command with a semi-colon which in some cases is useful but most of the time seems to be a really bad way of doing things (this is using Linux, BASH Shell, I expect Windows has similar mechanism).
Note that you don't seem to be able to set shell variables either, again using BASH:
x=10;echo $x
This works on the command line, running via system prints an empty line, may be possible but I've not managed it yet.
Also in your example, commands 1,2,3 and 4 are for the Operating System whilst commands 5 and 6 are for MySQL, try putting a semi-colon between each of your commands to see what happens.
My advice, if you are new-ish to PHP, is to try and avoid the system/exec/passthru functions and stick with in-built PHP libraries where-ever possible, most things you want to do can be handled by these libraries.
And additions to this are welcome, I'm no expert, just a few things I've noticed.
Toby

Billybob (2007-09-13 07:39:25)

Hi
I'm a newbie in php, and I was wondering if it's possible to use multiple line with "system". Here is an example:
$commandeDB1 = system ("cd \
cd mysql
cd bin
mysql -uroot -pedfdiver -P3307
use diver_1
insert into cdn_flv_8(flv_file,cdn_dn_or_ip,video_path,flv_groups
values('$fichier','130.98.61.32','/diver_edf/video_1/','0');");
Thanks

willytk at gmail dot com (2007-09-10 05:39:34)

If you're having problems with getting imagemagick/convert to work with ghostscript because the gs executable isn't in the apache PATH, do the following:

To create a thumb of the first pdf page:

<?php
$command
'export PATH=$PATH:/sw/bin; convert "files/example.pdf[0]" -thumbnail 150x150 "files/thumbs/example.png"';

$lastline system($command,$return);
?>

Thanks entropy.ch and phpaladin!

Regards,

Willy T. Koch
Oslo, Norway

timgolding_10 at hotmail dot com (2007-07-20 07:19:10)

An example of using the system to call the file command on a linux server. This script detects whether a user posted file is a jpeg, gif or png

<?PHP

$accepted_types
=array("JPEG" "GIF""PNG"); 

    
// The temporary filename of the file in which the uploaded file was stored on the server. 
if(!empty($_FILES["uploadedfile"]))
  {
    
$uploaddir $_SERVER['DOCUMENT_ROOT']."/images/";
    
$uploaddir.=basename$_FILES['uploadedfile']['name']);
   
 
//verfiy file using linux FILE command 
 
$last_line system('file '.escapeshellarg($_FILES['uploadedfile']['tmp_name']), $retval);

 
//get the file extension returned through magic database
 
$splitvals=explode(' image data' ,  $last_line);
 
$vals=explode(':'$splitvals[0]);
 
$vals[1]=str_replace(' ',''$vals[1]); 

 if (
in_array($vals[1], $accepted_types))
 {
    echo 
$vals[1].' was accepted <br />';
        if(!
file_exists($uploaddir)){
            
//Copy the file to some permanent location
            
if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $uploaddir))
             {
              echo 
$uploaddir." was uploaded! <br />";
             }
            else
             {
              echo 
"There was a problem when uploding the new file, please contact admin about this.";
             }
        }
        else echo 
'This file already exists in DB please rename file before uploading';
}
}else echo 
$_FILES['uploadedfile']['error'].'<br />';
?>

aaron at visual-code dot com (2007-07-01 04:41:34)

Regarding the running of processes in the background. i found that after a few different attempts that this worked fine and allowed the main script to continue unhindered.
Hope that this might help someone.
$arg1 = "arg1";
$arg2 = "arg2";
$page = "/path/tothe/script/scriptToRun.php";
$args = "--arg1='".urlencode($arg2)."' --arg2 ='".urlencode($arg2)."'";
$command = "(php -c /usr/local/lib/php.ini ".$page." ".$args." &) > /dev/null";
system($command);

eis (2007-06-20 02:11:40)

It should be noted, too, that "unable to fork" error in Windows also occurs if you try to send a command that's too long for cmd.exe to process.

peter at randomnity dot com (2007-03-28 09:09:13)

Just a note to dan at thecsl dot org

0 and FALSE are _NOT_ the same.
You can check for false like so:

<?php
if($return_val === FALSE) {
   
// ....
} else if ($return_val == 0) {
   
// ...
}
// Continue...
?>

jordan314 at mailinator dot com (2007-03-20 12:44:49)

z1a7n8g, your system logging to file function was really useful, but had two errors:
$line=fgets($fPtr,filesize("yourfile.php");
that line needs a second closing ')'
and:
while ($line)
returns true until your script runs out of memory. Those two lines can be combined:
while($line=fgets($fPtr,filesize("yourfile.php")));

norman_ss at hotmail dot com (2007-03-08 03:43:35)

thanks to tr4nc3,
I'm trying to, from the explorer, run an access's macro and this example give me the solution:
You can execute a .bat file with the especifications that give us tr4nc3.
After, in this .bat file, you can execute msacces.exe and pass /x parameter with the name of the macro. like this:
"c:\windows\system32\cmd.exe /c <path or the msaccess.exe>" <path of the .mdb file> /x <name of the macro>"
At the end of the .bat file you have to put "exit" and the thread will end.
Thanks to tr4nc3!

dotmg at wikkàwiki dot ORG (2006-08-09 23:43:47)

In system($command), $command cannot contain no more than two doublequotes. (At least with 4.3.3, on Windows). IF the path+executable name contains any space (and thus enclosed in double quotes).

<?php
 
/**
  * This example works fine, there is only 2 double quotes
  */
  
system ("\"c:\\program files\\myapp\\myapp.exe\" params_for_myapp");
 
/** 
  * This one will fail, php will complain sthg like c:\\program is not an executable
  */
  
system ("\"c:\\program files\\myapp\\myapp.exe\" \"One param for myapp that contains space\"");
  
//
  /** 
   * If you want your script to be able to run with older version of PHP (like 4.3.3), this is a trick:
   * Save the command in a temporary file and call that file
   */
  
$tmpnam tempname($writable_dir"temp").".bat";
  
$fp fopen ($tmpnam"w");
  
fwrite($fp$command);
  
fclose ($fp);
  
system($tmpnam$status);
  
unlink($tmpnam);
?>

Note: In my preview, backslashes were gone!

dan at thecsl dot org (2006-05-29 08:45:12)

You probably want to check your system calls for errors. The convention is to return 0  for "no error" which is the same as FALSE which can be confusing. You need to do something like:

<?php
  $cmd 
"/usr/bin/pngtopnm $png_file > $pnm_file";
  
system($cmd,$return_value);
  (
$return_value == 0) or die("returned an error: $cmd");
?>

matt-php at cdsportland dot com (2006-01-17 21:15:06)

If using Windows with IIS and you're having problems with the system() and related commands, I found the easiest way to solve it was to modify the Authentication Method for the file (or directory) that uses the call and change the anonymous access user from the default (IUSR_IMAGE) to a user with enough permissions to execute the commands in the system call. This way, there is no need to give execute permissions to IUSR_IMAGE on cmd.exe (which opens up a security risk system-wide) or copy cmd.exe into your php directory (per the suggestions of others). Hope this helps someone!

151408626 dot unique at servux dot org (2005-12-19 02:56:49)

The documentation notes that for making a program running in the background: ... you have to make sure that the output of that program is redirected to a file or some other output stream ...

But simply redirecting the command's output to a fifo will also cause PHP to wait for the command to terminate, even if it is started in background.

After quite a bit of trial & error, however I figured out that the trick (mentioned in some other note) using parenthesis to regain control over an already redirected STDOUT does work here, too:

<?

// this will not execute the echo in background while continuing the PHP-script, 
//    as one might expect 
system("echo 'something' >$someFIFO &");

// however that will do the trick - the echo is run in background, waiting until the data is read 
//    from the FIFO, while your PHP-script continues execution, e.g. being able to open that 
//    FIFO for read without being blocked until some data will arrive!! 
system("(echo 'something' >$someFIFO) >/dev/null &");

?>

cho at stunt growth dot com (2005-11-03 13:20:32)

Note to the persons who suggested using backticks for gathering a return value from scripts via system().
Using Backticks is generally frowned upon for security sake. They can be exploited more easily.
Instead, why not use the exec() function with a return parameter specified as an array type. This will allow you to take the full string returned from your script (for example rsync) and return each line in an array.
like so:
$result = array();
exec( $cmd, &$result);
foreach ( $result as $v )
{
// parse, or do cool stuff
}
Hope this alternative brings you merriment.

vdweij at hotmail dot com (2005-08-09 02:41:01)

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).
This link gave me this information:
http://www.cpqlinux.com/redirect.html

Stuart Prescott (2005-05-11 22:14:39)

Note that for stderr redirection, you have to use double quotes (") not single quotes (') for the 2>&1 part at least.

<?
//e.g. the this will NOT do what you expect:
exec('mysqldump -h localhost ...... 2>&1', $output);

//but this will:
exec("mysqldump -h localhost ...... 2>&1", $output);
?>

*sigh*

(Sounds like a PHP bug to me..., or at least buggy docs!)

phil at pjhayward.net (2005-04-26 13:37:25)

On Windows XP, (possibly others)
If you are getting the unable to fork error, make sure the internet guest user has permission to read and execute the \Windows\System32\cmd.exe file.

admin at nabeelakhtar dot net (2005-04-23 19:13:18)

Windows XP (IIS) users: (Unable to fork Problem)
If you receive something like:
Warning: passthru() [function.passthru]: Unable to fork [dir] in c:\Inetpub\wwwroot\ping.php on line X
1. Copy CMD.EXE file from the Windows\System32\ folder to your PHP directory (c:\PHP\).
This should fix the problem.

cabel at panic dot com (2004-12-14 16:20:05)

We were using system() to call a Cocoa command-line binary from PHP using Mac OS X. The Cocoa binary was simply not working -- no error message, no logging, nothing, it would just die within moments of launching from the system() function and we'd get no results.
The answer now seems obvious -- we were hitting PHP's memory limit. We did not consider that PHP's memory limit would also extend to programs launched via system().
So, if your system() call is failing mysteriously and giving no results, after trying the obvious (permissions, executable, etc.) considering upping:
memory_limit
in your php.ini from 8M to something larger.

Shai Coleman (2004-12-08 16:11:01)

The easiest way to run a process in the background under Windows, is to use system() with the bgrun.exe utility, available from http://www.jukkis.net/bgrun/

roga at yoopee dot de (2004-09-24 09:58:15)

In combination with Zend Optimizer and Windows 2K/XP some programs may not run with system(), exec(), etc.
I tried to use a small tool for ejecting the cd tray and it did just nothing. Disabling Zend Optimizer solved it.

srawlinNOSPAM at magma dot ca (2004-09-04 13:29:13)

If you are running PHP in a chroot environment then the system (and passthru) function needs /bin/sh to be located in the chroot as well.

eric_REMOVE at movementmovement_REMOVE dot com (2004-05-21 12:56:26)

It's important to note that if you are running a series of system() commands in a loop, you need to include the second argument in order for them to run synchonously.
ie)
// this will execute process.php asynchronously; not waiting for completion before executing the next one.
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"");
}
// this will execute process.php 3 times, waiting for the prior command to complete before starting a new one
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"", $status);
}

beetung at yahoo dot com (2004-03-08 13:34:13)

Under Linux
exec() doesnt follow symbolic link when interpret by httpd...
I have my /home/www/cgi-bin --> soft linked to a samba mounted directory under /mnt/Downloads/www.site.com/cgi-bin
exec("/home/www/cgi-bin/runProg $a $b");
works ok when I execute the script using > php myscript.php but fails to show the output when run via the web browser.
When I give it the exact full path without the symbolic link
exec("/mnt/Downloads/www.site.com/cgi-bin/runProg $a $b");
everything works perfectly.

mortoray at ecircle-ag dot com (2004-03-04 03:55:40)

Do not use "system" if you use the "php.ini" option:
zlib.output_compression = On
Doing so will result in the browser receiving garbage (I'm guessing the headers/buffers get confused).
Use passthru in this case, it appears to work as intended.

tr4nc3 at msn dot com (2004-02-22 02:42:36)

I almost gave up trying to get Windows XP w/ Apache 2 to use either system(), or exec() to run a batch file.
If the batch file was this...
echo test > test.txt
it would work fine, creating test.txt...
but if the batch file was..
iexplore.exe "http://www.ibm.com"
I would get nothing. After hours and hours of messing around with this I figured it must be some type of permission problem. (dugh!)
Long story a little shorter.. You have to give Apache permission to "interact with the desktop".
Here's how...
Start>Run>services.msc
Right click "Apache...", select properties.
Click on the "LOG ON" tab
Check the box "Allow this service to interact with desktop"
Click OK
Restart Apache
Works great!
:D
HOPE THIS HELPS SOMEONE!
Too bad I didn't find a post like this before I figured it out myself. (I could have been working on something.)

djem at shadrinsk dot net (2004-02-17 05:04:34)

BUGFIX for the mysystem() function, posted by n-jones.

<?php
function syscall($command){
    if (
$proc popen("($command)2>&1","r")){
        while (!
feof($proc)) $result .= fgets($proc1000);
        
pclose($proc);
        return 
$result
        }
    }
?>

Hello from Russia! :)
djem.

diogaogv at icqmail dot com (2003-11-28 16:57:07)

a really useful use for import(); while running the server at ur own machine is taking a screenshot of you desktop and showing it to the guest !!!

<?
echo system("/usr/X11R6/bin/import -window root -display localhost:0 /mnt/d/Desenvolvimento/Desenvolvimento\ WWW/import/cache/imagem.jpg -quality 30" ." 2>&1");
?>
<img src="cache/imagem.jpg">

remember to set chmod 777 to your directory (called "cache" on my code). also do "xhost +" or you r gonna get a xlib error saying that it could not connect to x server at localhost...

the code is still too simple. i've just done it. e.g. you can improve a real cache system avoying more than one screenshot in a minute while...

that is it! hope u enjoy it ( rofl... =DDD ) ...

diogo86

tomlubbock at hotmail dot com (2003-11-02 18:07:49)

If you need to run root-level commands, such as to reboot a service, the utility 'sudo' will let you handle linux permissions. In our example we use 'sudo' to allow apache temporary root access to restart a service. We can then use:
system("sudo service dhcpd restart")
You also need to examine the /etc/sudoers file to specify what permissions to grant. Hope this helps someone!

morris_hirsch at hotmail dot com (2003-09-16 14:49:37)

another reason to use shell_exec instead of system is when the result is multiple lines such as grep or ls 

<?php

// this correctly sets answer string to all lines found
//$answer = shell_exec ("grep 'set of color names' *.php ");
//echo "answer = $answer";

// this passes all lines to output (they  show on page)
// and sets answer string to the final line
 
$sys system ("grep 'set of color names' *.php ");
 echo 
"sys =(($sys))";

?>

here is view/source resulting from system call

setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  //$answer = shell_exec ("grep 'set of color names' *.php ");
silly.php: $sys = system ("grep 'set of color names' *.php ");
sys =((silly.php: $sys = system ("grep 'set of color names' *.php ");))

and here is view source from using shell_exec instead

answer = setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  $answer = shell_exec ("grep 'set of color names' *.php ");
silly.php:// $sys = system ("grep 'set of color names' *.php ");

lc at _REMOVE__THIS_lc dot yi dot org (2003-09-09 17:24:08)

Re: cpmorris at hotmail dot com and WINNT.
I just spent some time learning to use the php system function. I managed to get long file names to work for me. It seems you need to take the same approach that batch files, WSH, and most other programming languages do under WinNT/2K/XP. Putting double quotes around the Path+Filename seems to work. So, something like this should have worked for you:
"c:\program files\apache group\apache2\bin\htpasswd"
Note that if you have parameters, they go OUTSIDE of the last quote. Oh, and don't forget to escape the slashes and quotes!
I don't know what htpasswd's params are, but let us pretend:
$cmd="\"c:\\program files\\apache group\\apache2\\bin\\htpasswd\" username password";
$str=system($cmd);
Hope this helps someone!
Leonard
http:\\www.lc.yi.org

Jim Belton (2003-08-26 13:58:22)

To run a full screen program from a PHP CLI script, redirect input from and output to /dev/tty. For example:
system("timeconfig > /dev/tty < /dev/tty");
System will wait for the program to finish before continuing.

chris at karakas-online dot de (2003-07-01 18:52:42)

If your PHP installation permits execution of commands through system() (e.g. you are not running in safe mode, or, if you are, safe_mode_exec_dir contains all the commands you need), you can trigger a backup of your MySQL database, just by pointing your browser to the following script:

<?php
  
// Enter your MySQL access data  
  
$host'dbhost';         
  
$user'dbuser';               
  
$pass'dbpassword';
  
$db=   'db';

  
$backupdir 'backups';   

  
// Compute day, month, year, hour and min.
  
$today getdate();
  
$day $today[mday];
  if (
$day 10) {
      
$day "0$day";
  }
  
$month $today[mon];
  if (
$month 10) {
      
$month "0$month";
  }
  
$year $today[year];
  
$hour $today[hours];
  
$min $today[minutes];
  
$sec "00";

  
// Execute mysqldump command.
  // It will produce a file named $db-$year$month$day-$hour$min.gz 
  // under $DOCUMENT_ROOT/$backupdir
  
system(sprintf
    
'mysqldump --opt -h %s -u %s -p%s %s | gzip > %s/%s/%s-%s%s%s-%s%s.gz',                                                  
    
$host,
    
$user,
    
$pass,
    
$db,
    
getenv('DOCUMENT_ROOT'),
    
$backupdir,
    
$db,
    
$year,
    
$month,
    
$day,
    
$hour,
    
$min
  
));  
  echo 
'+DONE';  
?> 

If you are not allowed cron access on the web server, you can set up your own cron job to periodically call the above script. If you don't have cron, or a similar functionality on your system, you can still modify the above script to inform the browser to reget the file every xxx hours. A poor man's cron, so to say ;-)

Of course, the $backupdir should at least be protected with a .htaccess file.

And of course, you are not going to backup a really large database this way, if your PHP has some timeout set (as is usually the case with web hosters).

d dot kraft at szo dot de (2003-03-10 02:18:53)

For PHP running inside a Webserver:
When calling a process via
system("your_process &");
to make it running in background, note that this process is killed when the webserver is restarted.

cnoelker at softpearls dot de (2003-03-05 06:13:11)

Hi,
some tips for using a system()-call for batch files on a windows computer:
* Write the path to the executable with double back-slashes, like so:
C:\\path\\to\\prog.exe
* If you are refering to other pathes, e.g. as a parameter, one back-slash works fine.
* Do not use SET for declaring parameters - this does not work! Example:
SET PATH="C:\path\to\lib"
echo path is %PATH%
This works fine when started from the comand line, but when called from PHP, the variable is just empty.

user at unknown dot com (2003-01-15 14:07:52)

a simple way to include a beep on the server-side whenever a page in viewed.
**contents of 'beeping' page**
require ("beep.php")

**contents of beep.php**
<?php
system 
("/home/site/exe/beep.executable");
// on windows system ("c:\beep.exe");
?>

n-jones at fredesign dot net (2002-08-04 15:08:28)

To have system output from both the STDERR and STDOUT, I've modified the function posted above by lowery@craiglowery.com
function mysystem($command) {
if (!($p=popen("($command)2>&1","r"))) {
return 126;
}
while (!feof($p)) {
$line=fgets($p,1000);
$out .= $line;
}
pclose($p);
return $out;
}
Now you can use mysystem() like;
$var = "cat ".$file;
echo mysystem($var);
$catfile = mysystem($var);
if (ereg("text", $catfile)) {
//stuff here;
}
N.Jones

a dot paul at bernardlabs dot com (2002-07-21 04:42:14)

Well system is a pretty interesting and useful function.
This might have been already pointed out by predessors but anyways, for anyone looking to execute command line queries from php or scripts in general, this function does the trick.
However while using the command, you have to always think in terms of the command you are using as the function and the parameters as the arguments.
So say I want to do a 'ls -ls' on /home/sites/sitexyz/www/$username
I could do a
system("ls -la \"/home/sites/sitexyz/www/$username\" ");
Its important to think of this as passing /home/sites/sitexyz/www/$username as an argument to the function ls -la .
Similarly, you could do a
system("cp -r \"/home/sites/sitexyz/www/$username\" \"/home/sites/sitexyz/www/$username2\" ");
But you then need to use 'chmod -R 777 to the directory you want to copy it to, which can be done by a
system("chmod -R 777 \"/home/sites/sitexyz/www/$username2\" ");
Now you can execute all the terminal commans via the php, however do realise the security concerns of using the same, especially when the operation is going to preceeded by some user input, so, you need to make sure you filter the inputs, or better not allow user intervention.

(2002-06-17 20:29:49)

The system() function does not consistently write to the int return_var. I highly recommend using the code from the post above it worked well for me.
---------------------------------------------
$a = `/bin/ls -a`;
note: the ` is a backtick, not a single quote
---------------------------------------------
This also works well in Perl so it is rather useful to know.

ed at lexingrad dot net (2002-06-12 06:11:03)

best use I have found for this function so far:

<?php
$fortune 
= `/usr/games/fortune -aeo`;
 
$var eregi_replace("\n""<br>"$fortune);

echo 
$var;
?>
that's with all the fortune's installed, including the dirty ones. the reg expression replace formats them correctly

roger at proproject dot com (2002-05-12 22:35:46)

For your in-house pages, I recommend redirecting stderr to stdout so you'll know if something goes wrong. Here's a real-life example:
system("/mysql_reboot 2>&1");

james at jsrobertson dot net (2002-03-26 11:48:27)

I've found a very useful technique for the system function. Say if you want to create a page of quotes and you have /usr/games/fortune available. Instead of spending time creating a database and populating it with thousands of quotes, you can just use:

<?php
system
('/usr/games/fortune');
?>

likewise if you want to list the files in your directory, say for example, Mp3's?

<?php
system
('ls /home/mp3 -l');
?>

basically

<?php
system
('any_command');
?>

z1a7n8g at / at a<o<l dot c<o<m (2002-03-20 20:22:32)

I am currently using a form driven administration
page to start an ftp server remotely from a web page in FreeBSD 4.5 using PHP 4.1.2 & apache 1.3.23. (Sorry guys, no CVS!!)
This code will emulate a CLI command from your browser (anywhere!!) and execute it if your PHP module/binary has the correct permissions...
<code><pre>
//your front end
<form ..your form stuff here...>
<input type="text" name=command>
<your additional form stuff>
///the gutz
<? 
 $arg=explode( " ", $command, 4 )
     if ($arg[0] = "system")
       { 
 system($arg[1] . " " . $arg[2] . " " . $arg[3]..etc);
            }?>
</code></pre>
This works, however it is simple and lacks any error output.
try:
<pre><code>
 <?system(command > /path/to/yourfile.php);
     $fPtr=@fopen("yourfile.php",r);
     $line=fgets($fPtr,filesize("yourfile.php");
        while ($line)
  {
        $formatted_line=ereg_replace("your favorite newline semantic","<BR>",$line);
        print $formatted_line;
                                     }

 ?>
</pre></code>
Keep in mind the SECURITY implications with the use of this and like scripts. You've been warned.

tk at taponet dot de (2002-02-20 07:17:39)

Beware:
if (! system($cmd)) {
print "error";
}
does not work!
Use
if (system($cmd) === false) {
...}
instead!

nospam at 1111-internet dot com (2002-02-06 22:47:03)

Here's a neat trick that exploits an inherent php anomaly... if you want to run a shell command but not have it take up two processes for the entire life of the command (a child for the shell and a grandchild for the command), add a "&" at the end of the command to kill the shell and leave the grandchild command running... Though it's a bit counterintuitive, php will continue to listen for the orphanized grandchild command's STDOUT as long as it continues to run, provided STDOUT hasn't been been redirected with a ">/some/file"...
Very helpful if you're in a low-process-quota situation - I might even go so far as to say that this benefit might warrant ALWAYS using a "&" in php Unix system command situations - though the jury's still out on that one...

ryan at seattleone dot com (2001-08-29 17:36:33)

I was trying to use the system command, and I couldnt get it to work, then it occured to me, send the stderr to a file to see what is really happening.
system( $command . " &> /tmp/error " );

nospam at php dot net (2000-07-24 05:57:12)

If you are trying to parse a CGI script to your webserver which needs arguments, take a look to the virtual() function .. it took me long before i found out it existed...
It's used like this:
<?php
virtual
("/cgi-bin/lastuser.cgi?argument");
?>
And that works excellent now for me

digitalturbulence at softhome dot net (2000-07-09 00:04:43)

If the command printf("%s",system($cmd)); doesn't work, check the httpd.error_log file in your /var/log directory. At my home, the system command can just load binary files in the directory /usr/lib/apache/bin
Stephan.

ccurtis at aet-usa dot com (1999-06-14 11:07:52)

If no headers have been printed, calling the system() function will flush the headers to the client and insert a newline; no further headers or cookies will be transferred to the browser. In version 3.0.7, you will not be warned that the Header() function failed, but will be warned if trying to set a cookie. If you want to continue to send headers after the function call, use exec() instead.

易百教程