0

I'm trying to run a .bat file using PHP from the command-line. I'm using Windows Vista Home Premium.

When I use the script on a file like ipconfig.exe, I get the output. However, when I run the .bat file, it gives me output of what is in the file but it doesn't execute it.

What is below works and give me output:

$runCommand = "C:\\WINDOWS\\system32\\ipconfig.exe";
$WshShell = new COM("WScript.Shell");
$output = $WshShell->Exec($runCommand)->StdOut->ReadAll;
echo "<p>$output</p>";

But this doesn't:

$runCommand = "C:\\Temp\\foo.bat";
$WshShell = new COM("WScript.Shell");
$output = $WshShell->Exec($runCommand)->StdOut->ReadAll;
echo "<p>$output</p>";

Here's what's in my foo.bat file:

C:/windows/system32/schtasks.exe /create /tn "TestTask" /tr "C:/Temp/configure.php" /sc minute /st 08:00:00

If I copy this and paste in my Windows Command Line, this command executes successfully.

Not sure what is going on. Kindly assist.

1
  • 1
    12 questions, 1 accepted answer. Please read the FAQ: stackoverflow.com/faq Commented Dec 7, 2010 at 18:25

1 Answer 1

1

That's because a bat file is a queued list of commands for a prompt. Try the following:

cmd /c myfile.bat

(it may be /k too, forget which executes and closes)

Also, duplicate of How do you run a .bat file from PHP?

EDIT

<?php
  // http://www.php.net/manual/en/function.exec.php#85930

  $_ = null;

  // If you care about the return value, use this:
    passthru("C:\\WINDOWS\\system32\\cmd.exe /c custom.bat",$_);
    header('Content-Type: text/plain');
    echo $_;
  // if you don't care, just use this:
    $_ = exec("C:\\WINDOWS\\system32\\cmd.exe /c custom.bat");
?>
Sign up to request clarification or add additional context in comments.

14 Comments

I replaced C:\\Temp\\foo.bat with C:\\WINDOWS\\system32\\cmd.exe /k C:\\Temp\\foo.bat but it still doesn't execute.
Please see the link I mentioned in my answer that points tot he other question relating to batch files and php. They have a wonderful example in the accepted answer.
I tried exec('C:\WINDOWS\system32\cmd.exe /c START C:\Temp\foo.bat', $out), but it crashed my Apache server. Not sure how you got that to work?!
Please see my updated answer. Also, be sure to mark it as accepted since I've googling and RTM'n for you.
Tried this: $_ = null; passthru("C:\\WINDOWS\\system32\\cmd.exe /c C:\\Temp\\foo.bat",$_); header('Content-Type: text/plain'); echo $_; Still not working.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.