0

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?

  • Why do you absolutely want to run these two commands at the same time if you can run these commands one after the other...? – Juan Jan 13 '23 at 14:43
  • @Juan This is the sample code. Of course, these two commands can be executed separately. I just use this code as an example. In essence, I want to know how to execute multiple commands at the same time. – small tomato Jan 13 '23 at 14:48
  • I can't speak to your problem, but I always point people to `proc_open` instead which gives you access to things like stdout and stderr to better debug things. – Chris Haas Jan 13 '23 at 15:05

1 Answers1

1

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";
MarcM
  • 2,173
  • 22
  • 32
  • Hello, thank you very much for your answer. According to your method, this problem has been solved. Thank you very much. But now I have a more difficult problem. I have been troubleshooting for several hours. I have a new question. Can you help me look at it? https://stackoverflow.com/questions/75112930/php-exec-cannot-execute-python-script – small tomato Jan 13 '23 at 18:07