需要帮助使用PHP执行.bat文件

I am trying to execute a .bat file (m.bat) using a simple php script:

<?php
if(isset($_POST['submit']))
{
echo exec('m.bat');
echo "Done!";
} else {
    ?>
<form action="" method="post">
<input type="submit" name="submit" value="Run">
</form>
<?php
}
?>

this just displays the content of the .bat file in the browser, and if I drop the 'echo' before 'exec' it does nothing at all. :(

exec() executes commands, but doesn't open files.

You need to read the content of m.bat in order to execute it.

Try this

$file = file_get_contents("m.bat");
$output = exec($file);
print_r($output);

Hope it helps.

Firstly, .bat files run on Windows. If your server isn't Windows, it won't run and will instead just return the contents of the file.

If you are on Windows, try the backtick operator:

echo `m.bat`;

Note those are backticks, not single quote marks. This is functionally equivalent to shell_exec()

Windows batch files don't execute themselves IIRC. You should run them through one of the two interpreters:

print shell_exec("cmd m.bat");

(Otherwise that's the same as using the backtick operator.)

For other users reading this - what helped for me:

The user running your Webserver need access to file. Maybe if you use Apache and the built-in system account for the service, it won't have permission to access to your .bat file. I've changed the user for the service to the local system administrator for testing and it works fine. This was the error.

Don't forget to check your webserver's error log!