-1

I am trying to run a .bat file from PHP in a WAMP server on Windows. Below is my code, the first "if" statement runs and prints "Successful" to the screen. So, the function "exec" is running, but no file has been copied. Any help or advice please.

// Function run bat file
private function run_bat(){

    $path = 'wamp\www\application\common\get_file.bat';
    $batchCmd = "C:\\".$path;
    echo "<br>".$batchCmd;
    //if(exec('cmd /c '.$batchCmd)){
    if(exec($batchCmd)){
        echo '<br>Successful';
        return TRUE;
    } else {
        echo '<br>Error in run bat';
        return FALSE;
    }
} // end function run bat file 

my bat file just copies one file to a new folder. The other file is on a networked drive.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
ThomasC
  • 97
  • 1
  • 11
  • `my bat file just copies one file to a new folder.` PHP can do that as well using the copy function. – Manuel Mannhardt Nov 14 '17 at 18:34
  • @ManuelMannhardt sometimes, a simple command is just for a testing purpose to minimal other issue, it does help to see how the foundation mechanism to work. For PHP calling a Windows batch file to success is not as simple as u may thought. – early Mar 27 '20 at 20:49

2 Answers2

0

To run a bat script, you should use cmd /c filename. So you have to change the code to something like this

$batchCmd = "cmd /c C:\\" . $path;
Philipp
  • 15,377
  • 4
  • 35
  • 52
  • with "$batchCmd = "cmd /c C:\\" . $path;" all I am getting is the same, Successful but no copied files. Does the bat need to be in the same folder as the php script? – ThomasC Nov 14 '17 at 18:47
0

You should probably run it like this

system("cmd /c C: path_to_your_file");

in your case

system("cmd /c  $batchCmd ");

or go for

exec("c:\WINDOWS\system32\cmd.exe /c START  $batchCmd" );
Novy
  • 1,436
  • 1
  • 14
  • 26
  • with "exec("c:\WINDOWS\system32\cmd.exe /c START $batchCmd" )" the window just says "waiting for localhost" and never comes back up. – ThomasC Nov 14 '17 at 18:46
  • Did you try it with simple quote exec('c:\WINDOWS\system32\cmd.exe /c START $batchCmd' ) – Novy Nov 14 '17 at 18:54
  • let me ask a stupid question did you bat file works without php? – Novy Nov 14 '17 at 18:56
  • yes, it runs without PHP, simple quotes it just runs and runs "waiting for localhost" – ThomasC Nov 14 '17 at 19:52
  • i would suggest changed your server name from localhost to 127.0.0.1 in database connection configuration. It seems that is a well known issue. Hope it will help – Novy Nov 15 '17 at 08:45