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?

3
  • Why do you absolutely want to run these two commands at the same time if you can run these commands one after the other...? Commented Jan 13, 2023 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. Commented Jan 13, 2023 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. Commented Jan 13, 2023 at 15:05

1 Answer 1

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";
Sign up to request clarification or add additional context in comments.

1 Comment

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? stackoverflow.com/questions/75112930/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.