通过命令行调用PHP脚本时发送请求参数


Send request parameters when calling a PHP script via command line

当你在浏览器中运行PHP脚本时它看起来像

http://somewebsite.com/yourscript?param1=val1&param2=val2.

我试图通过命令行实现同样的事情,而不必重写脚本以接受argv而不是$_REQUEST。有没有办法这样做:

php yourscript.php?param1=val1&param2=val2 

使您发送的参数显示在$_REQUEST变量中?

如果您不想修改正在运行的脚本,您可以使用-B参数指定参数,在输入文件之前指定要运行的代码。但是在这种情况下,您还必须添加-F标签来指定输入文件:

php -B "'$_REQUEST = array('param1' => 'val1', 'param2' => 'val2');" -F yourscript.php

这不是我的功劳,但我在我的bootstrap文件中采用了这个:

// Concatenate and parse string into $_REQUEST
if (php_sapi_name() === 'cli') {
    parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);
}

从命令行执行PHP文件时:

php yourscript.php param1=val1 param2=val2

上面的代码将键和值插入到$_REQUEST中,以便以后检索。

不,要做到这一点并不容易。web服务器将拆分请求字符串并将其传递给PHP解释器,PHP解释器随后将其存储在$_REQUEST数组中。

如果从命令行运行并且希望接受类似的参数,则必须自己解析它们。命令行传递参数的语法与HTTP完全不同。你可能想看看getopt

对于不考虑用户错误的暴力破解方法,您可以尝试以下代码片段:
<?php
foreach( $argv as $argument ) {
        if( $argument == $argv[ 0 ] ) continue;
        $pair = explode( "=", $argument );
        $variableName = substr( $pair[ 0 ], 2 );
        $variableValue = $pair[ 1 ];
        echo $variableName . " = " . $variableValue . "'n";
        // Optionally store the variable in $_REQUEST
        $_REQUEST[ $variableName ] = $variableValue;
}

像这样使用:

$ php test.php --param1=val1 --param2=val2
param1 = val1
param2 = val2

我写了一个简短的函数来处理这种情况-如果命令行参数存在并且$_REQUEST数组为空(即,当您从命令行运行脚本而不是通过web界面时),它会在键=值对中查找命令行参数,

Argv2Request($argv);
print_r($_REQUEST);
function Argv2Request($argv) {
    /*
      When $_REQUEST is empty and $argv is defined,
      interpret $argv[1]...$argv[n] as key => value pairs
      and load them into the $_REQUEST array
      This allows the php command line to subsitute for GET/POST values, e.g.
      php script.php animal=fish color=red number=1 has_car=true has_star=false
     */

    if ($argv !== NULL && sizeof($_REQUEST) == 0) {
        $argv0 = array_shift($argv); // first arg is different and is not needed
        foreach ($argv as $pair) {
            list ($k, $v) = split("=", $pair);
            $_REQUEST[$k] = $v;
        }
    }
}

函数注释中建议的示例输入是:

php script.php animal=fish color=red number=1 has_car=true has_star=false

生成输出:

Array
(
    [animal] => fish
    [color] => red
    [number] => 1
    [has_car] => true
    [has_star] => false
)