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.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?