如何在windows中使用exec和cmd?

时间:2013-12-19 11:03:38

标签: php shell

我该如何运行:

shell_exec('"C:\Program Files\gammu\bin\gammu.exe" --sendsms TEXT 06706177529 -text "halooo"');

用cmd?如果我在cmd中运行它,它的效果非常好。所以我想用exec和cmd运行它。我找到了像cmd c/这样的东西,但它是如何工作的?

1 个答案:

答案 0 :(得分:0)

您需要使用COM

$shell = new COM("WScript.Shell"); 
$exec = $shell->Run($cmd, 0, false);

这是一个简单的例子,如果您前往http://php.net/function.exec并查看一些人已发布解决方案的评论。

看一下这个评论http://www.php.net/manual/fr/function.exec.php#57538,提供了一个很好的函数来包装上面的代码。我会把它贴在这里以防万一。

<?php
define ('EXEC_TMP_DIR', 'C:\tmp');

function windExec($cmd,$mode=''){
    // runs a command line and returns
    // the output even for Wind XP SP2
    // example: $cmd = "fullpath.exe -arg1 -arg2"
    // $outputString = windExec($cmd, "FG");
    // OR windExec($cmd);
    // (no output since it runs in BG by default)
    // for output requires that EXEC_TMP_DIR be defined

    // Setup the command to run from "run"
    $cmdline = "cmd /C $cmd";

    // set-up the output and mode
    if ($mode=='FG'){
        $outputfile = EXEC_TMP_DIR . "\\" . time() . ".txt";
        $cmdline .= " > $outputfile";
        $m = true;
    }
    else $m = false;

    // Make a new instance of the COM object
    $WshShell = new COM("WScript.Shell");

    // Make the command window but dont show it.
    $oExec = $WshShell->Run($cmdline, 0, $m);

    if ($outputfile){
        // Read the tmp file.
        $retStr = file_get_contents($outputfile);
        // Delete the temp_file.
        unlink($outputfile);
    }
    else $retStr = "";

    return $retStr;
}