Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

exec

(PHP 3, PHP 4, PHP 5)

exec -- Execute an external program

Описание

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

exec() executes the given command.

Список параметров

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.

Возвращаемые значения

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.

Примеры

Пример 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');
?>

Примечания

Внимание

Если вы собираетесь передавать функции данные, отправленные пользователем, вы должны использовать функции escapeshellarg() или escapeshellcmd() для того, чтобы обезопасить исполнение команд.

Замечание: Если вы собираетесь использовать эту функцию в программе, работающей в качестве демона, убедитесь, что стандартный вывод функции направлен в файл или другой поток, в противном случае PHP зависнет вплоть до конца выполнения программы.

Замечание: В случае работы в безопасном режиме, вы можете запускать что-либо только в пределах safe_mode_exec_dir. В настоящее время, использование .. в пути запрещено

Внимание

В случае работы в безопасном режиме, все слова, следующие за начальной командой, рассматриваются как единый аргумент. То есть echo y | echo x будет работать как echo "y | echo x".



passthru> <escapeshellcmd
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
exec
feedback at nospam fraktus dot com
31-Jul-2007 11:53
When I tried to exec in my dreamhost virtual host nothing worked until I moved my binary outside of the web directory and then it worked without any problem. You may have the same problem.
bachya1208 at gmail dot com
31-Jul-2007 12:24
Does anyone know of any restrictions on using exec() in a virtual host?  I have complete control of my apache server, but obviously prefer to section content into virtual hosts.

exec() doesn't do anything when applied to code inside a virtual host for me...
Farhad Malekpour
26-Jul-2007 04:24
If you're trying to use exec in a script that uses signal SIGCHLD, (i.e. pcntl_signal(SIGCHLD,'sigHandler');) it will return -1 as the exit code of the command (although output is correct!). To resolve this remove the signal handler and add it again after exec. Code will be something like this:

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

Same solution can apply to system and passthru as well.
WindowsPHPUser
10-Jul-2007 11:42
I had trouble getting the program execution functions to work on a Windows server, even though it worked on my test machine.  Here is something that helped:

First, set the security permissions on the exe to allow USR_MachineName to execute the program.

Then I changed the 'Log on as Batch Job' local security policy to include the IUSR account (and rebooted).  After I made that change, the programs were allowed to run.

I also limited the permissions for the IUSR account to read and execute only.
asari at users dot sourceforge dot net
09-Jul-2007 02:35
zitan at mediasculpt dot net and vdweij at hotmail dot com:

To get only STDERR, I think it's enough:

some_command 2>&1 >/dev/null
matt at virb dot com
12-Jun-2007 01:06
It seems as though PHP will ignore signals while waiting for an exec() call to finish.
conrad
07-Jun-2007 10:02
Windows note: Despite people syaing that you CAN you CANNOT exec a .vbs windows script host (wsh) file using exec() - you need to execute your vbs file via a "windows link" (.lnk file - a bog standard shortcut)

ie: I right click and dragged my datapurge.vbs a few pixels to the side and chose "Create Shortcuts Here" and then deleted the autogenerated "Short cut to datapurge.vbs" and renamed it merely datapurge.vbs - bear in mind as far as php is concerend it's ACTUALLY called datapurge.vbs.lnk

however you will need to sleep(); your php page to make sure the .vbs has had time to run if you intend on using the vbs output (say a file your vbs made) this is becase the .lnk instantly runs and php immediately continues processing without barely skipping a beat even if the vbs takes yonks to run.

If you are wondering why anyone would ever WANT to run a .vbs from within .php I can see some reasons - there are various windows platform objects just not accesible from php. (and most php programmers know a little .asp though they would say they don't! so asp-a-like .vbs is the logical choice)
martinwinter77 at no-spam-please dot gmail dot com
12-May-2007 05:19
In response to Bob-PHP at HamsterRepublic dot com (18-Oct-2005 11:00):

Since exec() removes trailing whitespace, Bob suggested to use popen() instead. However, if you do not need the additional features of exec(), it is much simpler to just use shell_exec(), which does preserve trailing whitespace.
skchandon at skchandon dot com
25-Apr-2007 07:46
PHP Exec : Delete statement execution problem
If filename is blank for exec: delete statement then it hangs the php execution, hence have to trap it as follows
 
<?php
$fname
=$_POST["fname"];
 if (
$fname!="")                    //  TRAP
 
exec ("del c:\\temp\\$fname"); }
 
?>
Zack / Nog
22-Apr-2007 10:23
Hey guys, I just wanted to drop a note after spending , i dunno 6 hours or so on getting exec() to work on an outside program with Win2k3 on IIS6 and PHP installed as an ISAPI module. I originally had it installed with Ensim, but it got confusing, so after a while of it not working I installed the latest PHP 5 binaries.

First thing I did was download the latest PHP 5 Binaries for Windows, but NOT THE INSTALLER. I dunno what the installer does, but I read previously not to use it, so I set it up like that.

After that I went into IIS manager, clicked on Add Extensions, added .PHP and changed the executing location to c:\php\php5isapi.dll. Then I went into the website portion, right clicked on it, went to properties, clicked on the Home site tab, clicked Configure and added an extension with extention = .php and executable = c:\php\php5isapi.dll.

After this , the thing that FINALLY WORKED! was , well, see at first I setup permissions by adding IUSR_MyCompName to the allowed list, and checked Full control, so i thought it had permissions.... Well, it was being overwritten which is what bit me...

I went into the C: drive, and right clicked and went to Properties, clicked on the Security tab, and then clicked on Advanced in the bottom right. If you see any IUSR with Deny, simply remove it.

Then right click on c:\php and do the same, after all Deny's have been deleted (Which override allows, which was my issue), go into c:\php and open the security tab, make sure IUSR_yourcompname is added as allow, and then do the same for c:\yoursoftwarefolder\ so your software has the same permissions.

The deny thing on C: overriding my c:\folder with allow was blowing it all up for me, I deleted the deny and made sure IUSR_mycompname was with full control on my outside apps file, and VUALA !!!

Theres now some trouble with it asking for a confirmation, but i'll figure that out later, i can at least run it without troubles :)

ALSO! DO NOT FORGET! Add C:\php and C:\outsidesoftwarefolder as Environment Variables to the Path variable in your system. It's easy, just right click my comp, properties, click advanced tab, enviornment variable button at the bottom, in the second scrolling list find the one with name of lowercase path, double click it, and on the end, add a semi-colon to end the last folder and type your folder location

so if it was originally c:\test;c:\windows\system32   and you wanna add php, make it read c:\test;c:\windows\system32;c:\php

Hope this helps someone , the thing that helped the most was the Advanced button in the security tab and removing the denies, which take ownership OVER the allows.

... My 2 cents :)
sirnuke at gmail dot com
26-Sep-2006 10:26
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.

<?php
exec
("/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.
sinisa dot dukaric at gmail dot com
16-Aug-2006 07:10
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...

<code>
@exec("echo 'apache' | /usr/bin/sudo -u mail -S /var/www/html/mailset.sh $name");
</code>

"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.
lauri dot myllari at gmail dot com
13-Jul-2006 02:27
If you're getting random hangs with exec() or system(), see PHP bug #22526 (http://bugs.php.net/bug.php?id=22526) for a workaround.
Jelsamino
11-May-2006 05:41
If you need generate new data .htpasswd file:

$command="htpasswd -nb ".$login."".$password;
exec($command,$res);
echo $res[0];

Luck!!!!!!!
29-Mar-2006 04:12
I've done a C program to act as a "timeout controller" process, by forking itself and executing some other command received as parameter.

Then, in PHP I have a function that calls commands this way:

<?php
...
$command = "tout_controller <tout> <command_name> <command_args>"
exec($command,$status);
echo
"Exit status code of command is $status";
...
?>

I've noticed that exit status code returned from a C process is a "special" integer.

I wanted "command" exit status code to be returned to controller, and then controller to exit with same status code (to get this status from PHP).
Exit status was always 0 !!!

To solve this, i've found a C macro to use inside tout_controller:

<C code snippet>
..
waitpid(pid,&status,0); // wait for process that execs COMMAND
..
//exit(status); // that doesn't work
exit(WEXITSTATUS(ret)); // that's ok
..
</C code snippet>

It isn't exactly a PHP note, but may be useful to help some desperated programmer's ;)
hanno at theuprightape dot net
14-Feb-2006 04:10
(quoting rassehund) "Just find sudoers in your system and add there rights to NOBODY."

This is, of course, a MAJOR security risk. You don't need sudo if you use it like that, you might just as well change permissions for all commands and paths.

For remote server administration, if I don't use ssh, I would let root run cronjobs that look at configuration parameters which were set using a web interface, preferrably using a database (for comfort) and input checks (for security). The logging/status/statistical information that the cronjobs produce are also made available via a web interface.

That way, you don't have to perforate your security mechanisms. And one more personal opinion: sudo isn't that safe anyway: ever tried "sudo bash" or "sudo vi"? I would avoid using it, if you get groups and permissions right, you are not going to need it.
gmail.com [at] dmimms
01-Feb-2006 04:41
I just spent around 10 hours trying to figure out why sudo wouldn't work from exec.  It's because SELinux was enabled.  Changing that to permissive is the solution.
rassehund at gmail dot com
13-Dec-2005 12:34
I spent quite a lot time fixing problem of invoking scripts in Linux remotly. In the beginning I thought that it was a problem of exec() function, than I thought that something wrong in Apache server, cos through the web server you are NOBODY and have no rights to invoke scripts in Linux.

so for example in my php script I had such line :

exec ('pathToScript/script.sh &');

If to start my php script with such line in the linux shell like : php myphp.php everything is perfect. But if to do the same through the server than problem occurs.
I solved this problems with sudoers file in Linux. U needn't change anything in Apache or in php script. Just find sudoers in your system and add there rights to NOBODY.
amandato (at) gmail (period) com
06-Dec-2005 12:51
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.

Code utilizes the PsTools, found here: http://www.sysinternals.com/ntw2k/freeware/pstools.shtml

Copy and paste the following code into an include file:
<?php
// pstools.inc.php

   
function PsExecute($command, $timeout = 60, $sleep = 2) {
       
// First, execute the process, get the process ID
       
$pid = PsExec($command);
       
        if(
$pid === false )
            return
false;
       
       
$cur = 0;
       
// Second, loop for $timeout seconds checking if process is running
       
while( $cur < $timeout ) {
           
sleep($sleep);
           
$cur += $sleep;
           
// If process is no longer running, return true;
           
if( !PsExists($pid) )
                return
true; // Process must have exited, success!
       
}
       
       
// If process is still running after timeout, kill the process and return false
       
PsKill($pid);
        return
false;
    }
   
    function
PsExec($command) {
       
exec( dirname(__FILE__). "\\psexec.exe -s -d $command  2>&1", $output);

        while( list(,
$row) = each($output) ) {
           
$found = stripos($row, 'with process ID ');
            if(
$found )
                return
substr($row, $found, strlen($row)-$found-strlen('with process ID ')-1); // chop off last character '.' from line
       
}
       
        return
false;
    }
   
    function
PsExists($pid) {
       
exec( dirname(__FILE__). "\\pslist.exe $pid 2>&1", $output);

        while( list(,
$row) = each($output) ) {
           
$found = stristr($row, "process $pid was not found");
            if(
$found !== false )
                return
false;
        }
       
        return
true;
    }
   
    function
PsKill($pid) {
       
exec( dirname(__FILE__). "\\pskill.exe $pid", $output);
    }
?>

Place the above include file and the PsTools from (http://www.sysinternals.com/ntw2k/freeware/pstools.shtml) in the same directory.
simoncpu
29-Nov-2005 11:48
Sometimes, it is convenient to let exec() return the status of the executed command, rather than return the last line from the result of that command.  In Unix, just do:

    $ret = exec('foo; echo $?');

Remember not to overdo it though. ;)

[ simon.cpu ]
jkxx at mail dot bg
30-Oct-2005 11:31
In response to mbirth@webwriters.de's post:

"I now switched over to using exec('start /b ...') directly with the desired command (instead of writing it into a batch file and calling that) and played around with the line-length. Seems like the exec() command works with command-strings of up to 4096 characters in length. If the string is longer, it won't be executed."

I have had this issue ever since I started writing CGIs in Windows 2000 (NT 5.0 then). The "stdout" stream is subdivided into 4Kbyte chunks. As a result, when data is sent out by the CGI, there will be issues when that data goes over the 4K boundary. In my case I just appended enough whitespace to round the output to the nearest multiple of 4096 and all output made it to the destination. Not sure if this would be a practical solution for everyone, though.
Bob-PHP at HamsterRepublic dot com
18-Oct-2005 11:00
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.
clive at pluton dot co dot uk
15-Oct-2005 03:35
When trying to run an external command-line application in Windows 2000 (Using IIS), I found that it was behaving differently from when I manually ran it from a DOS prompt.

Turned out to be an issue with the process protection. Actually, it wasn't the application itself that was having the problem but one it ran below it! To fix it, open computer management, right-click on Default Web Site, select the Home Directory tab and change Application Protection to 'Low (IIS Process)'.

Note, this is a rather dangerous thing to do, but in cases where it's the only option...
rivera at spamjoy dot unr dot edu
06-Oct-2005 01:17
windExec() reloaded:
* unique timestamp name was probably a good idea for multiple instances of function running @ same time
* includes handy FG/BG parameter

<?php
define
('EXEC_TMP_DIR', 'C:\tmp');

function
windExec($cmd,$mode=''){
   
// runs a command line and returns
    // the output even for Wind XP SP2
    // example: $cmd = "fullpath.exe -arg1 -arg2"
    // $outputString = windExec($cmd, "FG");
    // OR windExec($cmd);
    // (no output since it runs in BG by default)
    // for output requires that EXEC_TMP_DIR be defined

    // Setup the command to run from "run"
   
$cmdline = "cmd /C $cmd";

   
// set-up the output and mode
   
if ($mode=='FG'){
       
$outputfile = EXEC_TMP_DIR . "\\" . time() . ".txt";
       
$cmdline .= " > $outputfile";
       
$m = true;
    }
    else
$m = false;

   
// Make a new instance of the COM object
   
$WshShell = new COM("WScript.Shell");

   
// Make the command window but dont show it.
   
$oExec = $WshShell->Run($cmdline, 0, $m);

    if (
$outputfile){
       
// Read the tmp file.
       
$retStr = file_get_contents($outputfile);
       
// Delete the temp_file.
       
unlink($outputfile);
    }
    else
$retStr = "";

    return
$retStr;
}
ewilde
20-Sep-2005 04:55
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:

  if (!($ProgInfo = apache_lookup_uri(/cgi-bin/myprog)))
    $ProgPath = /usr/bin/myprog;
  else
    {
    if (is_object($ProgInfo)) $ProgPath = $ProgInfo->filename;
    else $ProgPath = $ProgInfo["filename"];
    }

exec("$ProgPath ...");
mbirth at webwriters.de
13-Sep-2005 11:42
I had to combine many PDFs into a single one using pdftk and did this by writing the commands into a batch file and running it with exec('cmd /c blabla.cmd').

Using batch files under Windows, there's a line-length-limit of 1024 characters. So I made sure each line in the batch file doesn't exceed 1024 characters.

I now switched over to using exec('start /b ...') directly with the desired command (instead of writing it into a batch file and calling that) and played around with the line-length. Seems like the exec() command works with command-strings of up to 4096 characters in length. If the string is longer, it won't be executed.
nonnsi at gmail dot com
13-Sep-2005 12:25
I found this site to be very helpful when trying to add parameters to the "start" command in windows xp.
http://www.robvanderwoude.com/ntstart.html
I use:
exec( 'start "title" /Dpath /B program parameters' );
CJ [AT] TBG
08-Sep-2005 10:41
[EXEC] on [Windows]

Finally a simple way to get exec working w/o launching a black box window.

just do: exec('start /B "window_name" "path to your exe"',$output,$return);

The important part is the /B which makes it run in the background.
p dot koeman at wittenborg-university dot com
29-Aug-2005 06:22
Using sudo (http://www.sudo.ws/) to exec system commands from PHP

This is a secure way to use sudo from PHP to perform sysadmin tasks from a php webapplication. (can be used with exec or passthru)

- Make a PHP script in the WWW root directory : client.php

[/home/mywebdir/html/client.php]
<?
passthru('echo hello world | sudo /usr/bin/php -f /home/server.php');
?>

- Make a PHP script outside the WWW directory : server.php

[/home/server.php]
<?
echo join('',file('php://stdin'));
?>

Add a line to /etc/sudoers

[in /etc/sudoers]
www    ALL=(ALL) NOPASSWD: /usr/bin/php -f /home/server.php

Now execute client.php in the webbrowser (as www user)
- client.php will execute sudo
- sudo will execute server.php by php as root !

In server.php you can do everything you like requiring root privileges. BEWARE ! every php script can now execute server.php, make it secure ! (filter parameters etc.)

I have tested this method and it works !
Kind regards, Pim Koeman
Wittenborg-University, Deventer, the Netherlands
http://www.wittenborg-university.com
vdweij at hotmail dot com
09-Aug-2005 04:18
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
juha at kuhazor dot idlegames dot com
03-Aug-2005 11:32
This technique was post posted by someone else earlier, however it did not work for me. This works with all Linux distros as long as path to your PHP processor is correct. The exec will return the PID for the process.

<?
$pid=exec("/usr/local/bin/php run.php > /dev/null & echo \$!");

echo $pid;
?>

My run.php script is here, it is good for testing.

<?

function getmicrotime()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

$starttime = getmicrotime();

$date=date("d/m/Y H:i",time());

echo "Started sleeping\n";
sleep(30);
$endtime = getmicrotime();
echo "Woke up\n";

echo "Slept ".round(($endtime-$starttime),2)."\n";

?>
netshadow at madpoets dot org
05-Apr-2005 07:13
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.

What I finally wound up doing was using psexec from the pstools package found at http://www.sysinternals.com/ntw2k/freeware/pstools.shtml

You would use it like:

exec("psexec -d blah.bat");

which will start and immediately background blah.bat and immediately resume running the rest of the php script.
bitminer at example dot com
19-Mar-2005 10:24
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 privileges
chmod 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 server
Xlib: 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

To
apache:x:48:48:Apache:/var/www:/bin/bash

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

su apache
xmms
!!! 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

<?php
echo ' Executing XMMS ';
// note you could use system too!
//echo system( '/usr/bin/xmms --play icould.wav', $retval );
exec ('/usr/bin/xmms --play icould.wav');
?>

At your browser ensure you hit shift+refresh(button) so your browser doesn't give you a cahed the web page.

Brian J. Davis
david houlder
22-Feb-2005 03:47
The note regarding how exec() works under safe_mode is wrong.

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.
xyexz at yahoo dot com
21-Jan-2005 10:28
Ok, well after looking around for a long time on how to execute programs and not have them hanging in the processes in windows I have come up with a solution thats good for me but some of you may laugh.
Credit to msheakoski @t yahoo d@t com for the example script above here somewhere.
My problem was that I sometimes restart my server remotely and it doesn't turn on my ftp when my computer starts up, I do this so it will start up quicker.  But when I want my ftp open I was using a script that executed a .bat from php.  However I found this leaves processes running that were dead.
I saw msheakoski's solution:

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

Well I tried sticking in my ftp program executible name where he had notepad.exe.
It didn't work.
Then I realized that windows will execute anything in the windows directory without including the entire path.
So I made a lnk file called FTP.link.  I then edited msheakoski's script to:

<?
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("FTP.lnk", 3, false);
?>

And voila! It runs my ftp program and cmd nor php.exe run in the background dead. Simple yet effective, (just how I like it).
Hope this helps you as much as it did me.
Brian
layton at layton dot tk
18-Jan-2005 03:52
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.
13-Jan-2005 04:38
I wanted my script to:

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

This is the code I use:

<?php

$com
= "ls";     # command

exec("$com 2>&1", $out, $err);                                          
if (
$err) my_log_func(join("\n", $out));

?>
chads2k2.yahoo.com
13-Dec-2004 10:38
This will execute a exectuable from the
command window without the command
window even being seen.

Much help was given by Michael Sheakoski
as he stated below this in one of his other
scripts.  The problem I had was that I want
to have arguments be sent to the .exe.

This will run the exe and then whatever it
returned will be dealt with.

Tested with:
Windows XP Pro SP1
Apache2
PHP 4.3.x
IIS6 as well

Here is the snippet.
<?php
// Get a good ol' timestamp.  Unique and it works.
$unixtime = time();

// Sets up your exe or other path.
$cmd = 'C:\\path\\to\\program\\argue2.exe';

// Setup an array of arguments to be sent.
$arg[] = '1';
$arg[] = '2';
$arg[] = '3';
$arg[] = '4';
$arg[] = '5';

// Pick a place for the temp_file to be placed.
$outputfile = 'C:\\path\\to\\tmp\\unixtime.txt';

// Setup the command to run from "run"
$cmdline = "cmd /C $cmd " . implode(' ', $arg) . " > $outputfile";

// Make a new instance of the COM object
$WshShell = new COM("WScript.Shell"); 

// Make the command window but don't show it.
$oExec = $WshShell->Run($cmdline, 0, true);

// Read the file file.
$output = file($outputfile);

// Delete the temp_file.
unlink($outputfile);

// Take the output and break the array apart. 
// If you don't know what is coming out do:
// print_r("$output");
foreach($output as $temp_output)
{
  
// Check the output's return code.
  
if($temp_output == 1)
   {
     
// Tell the user it was correct.
     
echo "All is good";
   }else{
     
// Tell the user something goofed.
     
echo "Didn't go smoothly.";
   }
}
?>
13-Oct-2004 09:46
if you want to use rsh and nohup, you should do this:

<?php
  
//...
  
exec("nohup  rsh -n *command* 1>/dev/null/ 2>&1 &");
  
//..
?>

or

<?php
  
//...
  
exec("nohup  rsh -n *command* 1>result.log 2>&1 &");
  
//...
?>
php-contrib at i-ps dot net
12-Oct-2004 06:30
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.

1) PHP script file exists:
  c:\www\script.php

2) PHP is installed in:
  c:\www\php\

3) BAT file contains:
  @c:\www\php\cli\php.exe c:\www\script.php %1

and is saved as:
  c:\www\script.bat

4) Use exec statement from PHP:
  exec("c:\www\script.bat $arg", $output);

If you want to pass more than one argument, carry on with %2, %3, %4, ..., ... in your BAT file.

Hope this helps somebody
msheakoski @t yahoo d@t com
08-Jul-2004 08:40
I too wrestled with getting a program to run in the background in Windows while the script continues to execute.  This method unlike the other solutions allows you to start any program minimized, maximized, or with no window at all.  llbra@phpbrasil's solution does work but it sometimes produces an unwanted window on the desktop when you really want the task to run hidden.

start Notepad.exe minimized in the background:
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("notepad.exe", 7, false);

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

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

For more info on the Run() method go to:
http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp
llbra@phpbrasil
05-Jul-2004 05:30
If you want to run somenthing but php just keep processing data and don
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571