I use PHP in Windows 11. I need to execute multiple commands in PHP exec.
My sample code is as follows:
$output=null;
$result_code=null;
exec("cd E:/Python/WordFrequency ; ipconfig", $output, $result_code);
return $result_code;
The return error code is 1.
However, if only one command is executed, it can work normally:
exec("cd E:/Python/WordFrequency", $output, $result_code);
Or:
exec("ipconfig", $output, $result_code);
Return codes are all 0.
However, if the two commands are concatenated, code 1 will be returned.
I have tried ";" Replace with "&&", and/or set the command with escapeshellcmd or escapeshellarg, as follows:
exec(escapeshellcmd("cd E:/Python/WordFrequency ; ipconfig"), $output, $result_code);
But the result is the same, and the error code 1 is returned.
What's the matter, please?
CodePudding user response:
Use:
<?php
$commands = "command1.exe && command2.exe && command3.exe";
exec($commands, $output, $result_code);
if ($result_code!== 0) {
throw new Exception("Failed to execute commands: $commands");
}
var_dump($output); // the output from the commands
The && operator is used in Windows Command Prompt to run multiple commands one after another. You can also consider using the & operator, to run multiple commands simultaneously.
Using it this way, you should have the same results as running it manually in the Windows command line.
Side note: I wonder if the environment is set exactly the same as in the Windows command line. In other words: environment variables such as %PATH%
might be not informed. In case you have problems make sure to add the full path to the commands. For instance:
$commands = "c:\folder1\command1.exe && c:\folder2\command2.exe";