4

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?

jww
  • 97,681
  • 90
  • 411
  • 885
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
  • [added comment again because the link was borked] Won't enclosing the .cmd file in backticks do it, like the example with the .bat file here? http://www.php.net/manual/pl/language.operators.execution.php – sigint Jul 18 '09 at 02:39
  • 1
    Something like this? I don't have PHP handy right now so can't test this, sorry! $test"; ?> – sigint Jul 18 '09 at 02:46
  • @hamlin11 - What doesn't work about it("print `ls`;")? I just tested it(on a linux machine, though) and it worked fine for me. Try: – Ian P Jul 18 '09 at 02:47
  • just curious, what does the cmd file do? – ghostdog74 Jul 18 '09 at 02:56
  • runs 7zip and does a few file management things – Brian Webster Jul 18 '09 at 04:10
  • Related, [How do you run a .bat file from PHP?](http://stackoverflow.com/q/835941) – jww Nov 15 '16 at 04:05

5 Answers5

4

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
  • 29,093
  • 5
  • 52
  • 80
2
$result = `whatever.cmd`;
print $result; // Prints the result of running "whatever.cmd"
Ian P
  • 1,512
  • 3
  • 15
  • 18
2

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
  • 59,775
  • 49
  • 126
  • 179
1

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
  • 395,085
  • 80
  • 655
  • 663
1

Use the php popen() function

Steve
  • 51
  • 2
  • 5