mgat
mgat

Reputation: 91

execute .bat file from php in background

I try to execute a .bat file (Windows Server with xampp) from php in Background. After i klick on the button, it also should go to another Website. But when i click on the button, the browser is waiting for the script to finish. Mostly this is ending in a timeout.

my php code:

if (isset($_POST['test']))
{
    exec('C:\Daten\test.bat');
    header("Location:test_status.php");
}

how can i tell the php exec, to dont wait?

I tried also following, but does not work:

exec('C:\Daten\test.bat' . '> /dev/null &');

Upvotes: 0

Views: 9336

Answers (3)

Rodgers Andati
Rodgers Andati

Reputation: 151

This worked for me.

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

Upvotes: 1

mgat
mgat

Reputation: 91

Thanks for the response, but this did not work for me. I found that many solution ideas in the internet, but nothing worked for me.

Now i finally found the solution! The keyword is popen! This works nice:

$handle = popen ('start /B C:\Data\restart_TS3.bat > C:\Daten\restart_TS3.log 2>&1', 'r');
pclose ($handle);
header("Location:ts3_status.php");

This do following: popen opens a background process that starts the batch file, output goes to the log file. Then you need to close it with pclose. (the batch is still running in background) After that, it opens another website, in my case its a "see current status" website.

If you dont want a log, you can also output (like MarkB told before) with >nul. This would look like that:

$handle = popen ('start /B C:\Data\restart_TS3.bat >nul 2>&1', 'r');

And be careful with empty spaces in the path! I dont know why, but this will not work:'start /B "C:\Data Folder\restart_TS3.bat" >nul 2>&1' In that cases you need " in the folder like that:

$handle = popen ('start /B C:\"Data Folder"\restart_TS3.bat >nul 2>&1', 'r');

This works fine with empty space in Folder names.

Upvotes: 2

Marc B
Marc B

Reputation: 360812

You're using Windows. there's no /dev/null in Windows (it's just nul), and there's no & to run jobs in the background. & in cmd.exe is a command separator. So your exec() will hang/wait for the .bat to finish.

Try

exec('start c:\daten\test.bat');

instead, which would start the batch file as a separate process.

Upvotes: 1

Related Questions