dongyuli4538 2013-08-06 10:52
浏览 203

使用PHP在命令提示符下运行.bat文件

I need to run a .bat file in a command prompt whenever I click a button or hyperlink. The code I've written is:

<?php
    if(isset($_POST['submit']))
    {
        $param_val = 1;
        $test='main.bat $par'; 
        // exec('c:\WINDOWS\system32\cmd.exe /c START C:/wamp/www/demo/m.bat');    
        // exec('cmd /c C:/wamp/www/demo/m.bat');
        // exec('C:/WINDOWS/system32/cmd.exe');
        // exec('cmd.exe /c C:/wamp/www/demo/main.bat');
        exec('$test');
    } 
    else
    {
        ?>

        <form action="" method="post">
        <input type="submit" name="submit" value="Run">
        </form>

        <?php
    }
?>

my main.bat is:

@echo off
cls
:start
echo.
echo 1.append date and time into log file
echo 2.just ping google.com

set/p choice="select your option?"

if '%choice%'=='1' goto :choice1
if '%choice%'=='2' goto :choice2
echo "%choice%" is not a valid option. Please try again.
echo.
goto start
:choice1
call append.bat
goto end
:choice2
call try.bat
goto end
:end
pause

When I click the run button it has to open the command prompt and run the main.bat file, but whenever I click run it says nothing.

  • 写回答

4条回答

  • dqx36753 2013-08-06 10:54
    关注
    $test='main.bat $par';
    exec('$test');
    

    ... won't work.

    PHP only takes $variables in double quotation marks.

    This is bad practice also: $test = "main.bat $par";.

    Also windows takes backslashes instead of slashes which need to be escaped through another backslash in double quotes.

    Use one of these:

    $test = 'cmd /c C:\wamp\www\demo\main.bat ' . $par;
    

    or

    $test = "cmd /c C:\\wamp\\www\\demo\\main.bat {$par}";
    

    run:

    echo shell_exec($test);
    

    Even more fails:

    Remove the pause from the end of your script. PHP does not get arround that automatically.

    Looking more at the batch file, I bet you don't even need it. Everything inside the batch file can be put into a PHP file.

    As Elias Van Ootegem already mentioned, you would need to pipe in STDIN to enter your option (1, 2) into the batch file.

    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样