Nikunj K.
Nikunj K.

Reputation: 9199

How to execute batch file via PHP?

I tried to execute the batch file using exec command in PHP. I just used it like:

$filename = 'test.bat';
exec($filename);

But didn't get any output. I tried this function with another command, it works fine. Your suggestions would be highly appreciated. Thanks

Upvotes: 5

Views: 43353

Answers (6)

Mark Giblin
Mark Giblin

Reputation: 1106

What I did was the following:

  1. created a PHP file that contained :

    $gotIt = array();
    $file = "getMyIP.bat";
    exec( $file, $gotIt );
    echo implode("<br>",$gotIt);
    
  2. Created a batchfile in the same folder

    @ECHO off
    ipconfig
    
  3. Ran it and waited for the firewall to jump all over the action.

I then got an output like :

Windows IP Configuration


PPP adapter 3 USB Modem:

Connection-specific DNS Suffix . :
IP Address. . . . . . . . . . . . : ***.***.202.81
Subnet Mask . . . . . . . . . . . : 255.255.255.255
Default Gateway . . . . . . . . . : ***.***.202.81

only theres numbers where the ***'s are

Upvotes: 1

Milan
Milan

Reputation: 3335

On Windows server mind the quotes. This is what works for me:

system('cmd.exe /c C:\myfolder\_batches\run_this_batch.bat');

Upvotes: 2

fluminis
fluminis

Reputation: 4059

As it is explained in the exec doc:

echo exec($filename);

or

exec($filename, $output);
echo $output;

Upvotes: 0

Nikunj K.
Nikunj K.

Reputation: 9199

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.

Upvotes: 7

Katran
Katran

Reputation: 86

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

https://www.php.net/manual/en/function.passthru.php

Upvotes: 1

Ruddy
Ruddy

Reputation: 9923

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

As "RichieHindle" said in a similar topic.

or try

exec("cmd.exe /c test.bat") ?

Upvotes: 1

Related Questions