How to Run a .Bat File from PHP

How do you run a .bat file from PHP?

You might need to run it via cmd, eg:

system("cmd /c C:[path to file]");

How to execute batch file via PHP?

The main issue was of path and permission. I have gotten my batch file to execute.

Here is my solution:

  1. I run my batch file from the same folder the php file is in.

    exec("mybatch.bat");

  2. I make sure that Apache Service has enough permission to run the batch file. Just to test i used an administrator account for Apache to log on with.

Open batch file php

In php manual about exec function, there is a note :

Note: If a program is started with this function, in order for it to
continue running in the background, the output of the program must be
redirected to a file or another output stream. Failing to do so will
cause PHP to hang until the execution of the program ends.

I think "hangs like the application is loading" is your application waiting for the bat file terminated / closed to get the output result

Let's try another approach, i found it here, the concept is to create a scheduler that execute the program you want and call it using command.

hope this help :

shell_exec('SCHTASKS /F /Create /TN _notepad /TR "notepad.exe" /SC DAILY /RU INTERACTIVE');
shell_exec('SCHTASKS /RUN /TN "_notepad"');
shell_exec('SCHTASKS /DELETE /TN "_notepad" /F');

If this doesn't work

Check whether you have declared safe_mode = Off inside php.ini

How to run batch file using php?

Are you tried this?

system("cmd /C X:[PATH_TO_BAT_FILE]", &$output);

Where parameter

/C = Carries out the command specified by the string and then terminates

&$output = Return value

In your case

$gotIt = array();
$file111 = "C:/ABC/run.bat";

/** CMD cant return directly Array, but Text */
$CMDOutput = "";
system("cmd /C \"$file111\"", $CMDOutput);

/** Split output as you want (With Token, with preg_match, ...) */
$gotIt = mySplitFunction($CMDOutput);

/**
* EX. with explode where first param is a token (delimiter)
*
* If $CMDOutput contains "Pietro, terracciano", with this
* instruction you obtain
* $gotIt = array(
* 'Pietro', 'Terracciano'
* );
*/
$gotIt = explode(',', $CMDOutput);

/** ... */

Running a php script with a .bat file

The START command optionally accepts a title for the created window as its first argument; in this case, it thinks that C:\Program Files (x86)\PHP\v5.3\php.exe is the title to display and -f (the second argument) is the executable you want to run.

You can therefore fix this by providing a placeholder title, e.g.

start "email reminder task" "C:\Program Files (x86)\PHP\v5.3\php.exe" -f C:\inetpub\wwwroot\sitename\crons\reminder-email.php

Or, preferably, you can ditch the START command altogether (you aren't using any of its unique facilities) and just run PHP directly:

"C:\Program Files (x86)\PHP\v5.3\php.exe" -f C:\inetpub\wwwroot\sitename\crons\reminder-email.php


Related Topics



Leave a reply



Submit