如何使用PHP运行批处理文件?

i have tried opening .bat files in PHP using many syntax and they are working fine. It runs the file and stores the output. But im having a new problem in hand where i need to initiate a server program from PHP.

Lets say i have a the server program "server.java" and a client program "client.java". The server needs to be run first and then the client. I have created a batch file to run this server program as "server.bat". Is it possible to initiate this server.bat file from the PHP side and make it run in the background until the client finish its process?

Try exec("psexec -d server.bat");

You're looking for the exec function.

Be aware of a few dangers with this function, namely:

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note: If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Reading Output

The exec command has an optional variable called $output which can be used to display the output of the command run via PHP. However, this only works after the sub-process (in this case the batch file) exits, which does not work for a Server script.

To display information while the script is still running we must redirect the output of the script to a file and then read that file. To demonstrate this, we'll take our example:

exec("server.bat");

and add a redirect to "server_log.txt"

exec("server.bat > server_log.txt");

Once this is running we can check the output of the batch file by reading "server_log.txt" A good (if somewhat dated) tutorial on reading files from PHP can be found here.

I got this to work by executing the following code:

exec("start cmd /c test.bat", $output);
var_dump($output);