How to execute batch file via PHP?

41,385

Solution 1

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.

Solution 2

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

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

Solution 3

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.

http://md1.php.net/manual/en/function.passthru.php

Solution 4

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

As "RichieHindle" said in a similar topic.

or try

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

Solution 5

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

Share:
41,385
Nikunj K.
Author by

Nikunj K.

Dear Mr. / Mrs. / Ms. I am SR. PHP DEVELOPER in the areas of Project Management &amp; Web/Software Development and Service Delivery. I am a solutions-oriented person who thrives in challenging, fast-paced environments where my performance directly impacts the bottom line. I believe that my strong background in IT combined with my extensive experience in planning, executing, monitoring, and closing a variety of projects, which makes me ideally suited to this role. I bring to your company my years of relevant experience and my drive for results and positive outcomes. I am prepared for the next challenge in my career and look forward to hearing from you. Thank you for your time and consideration.

Updated on November 12, 2020

Comments

  • Nikunj K.
    Nikunj K. over 3 years

    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

  • Admin
    Admin over 10 years
    Correct solutions, Both Batch file and php files are in same folder