How to run .cmd file from PHP and display results

I need to run the .cmd batch file from php script.

PHP will be available through an authenticated browser session.

When I run the .cmd file from the server desktop, it spills out some output in cmd.exe.

I would like to redirect this output to a php page.

Is this doable?

+4
source share
5 answers

Yes, it is doable. you can use

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

and print the contents of the array:

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

look here for more information

+4
source
 $result = `whatever.cmd`; print $result; // Prints the result of running "whatever.cmd" 
+2
source

I prefer to use popen for this kind of task. Especially for long commands, because you can receive output in turn and send it to the browser, so there is less chance of a timeout. Here is an example:

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

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

If you want to pass parameters to this command, you must use escapeshellargs to avoid them before invoking the command; and you can take a look at escapeshellcmd too ^^

+1
source

Use php popen () function

+1
source

All Articles