views:

1635

answers:

5

I need to run a .cmd batch file from within a php script. The PHP will be accessed via an authenticated session within a browser.

When I run the .cmd file from the desktop of the server, it spits out some output to cmd.exe. I'd like to route this output back to the php page.

Is this doable?

Thanks in advance for your time.

+2  A: 

Yes it is doable. You can use

exec("mycommand.cmd", &$outputArray);

and print the content of the array:

echo implode("\n", $outputArray);

look here for more info

Peter Parker
+2  A: 
$result = `whatever.cmd`;
print $result; // Prints the result of running "whatever.cmd"
Ian P
+1  A: 

You can use shell_exec, or the backticks operator, to launch a command and get the output as a string.

If you want to pass parameters to that command, you should envisage using escapeshellargs to escape them before calling the command ; and you might take a look at escapeshellcmd too ^^

Pascal MARTIN
+1  A: 

Use the php popen() function

Steve
+2  A: 

I prefer to use popen for this kind of task. Especially for long-running commands, because you can fetch output line-by-line and send it to browser, so there is less chance of timeout. Here's an example:

$p = popen('script.cmd', 'r');
if ($p)
{
    while (!feof($p))
        echo gets($p);    // get output line-by-line
    pclose($p);
}
Milan Babuškov