通过命令行调用PHP脚本时发送请求参数 [英] Send request parameters when calling a PHP script via command line

查看:87
本文介绍了通过命令行调用PHP脚本时发送请求参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您通过浏览器运行PHP脚本时,它看起来像

When you run a PHP script through a browser it looks something like

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

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

I am trying to achieve the same thing via command line without having to rewrite the script to accept argv instead of $_REQUEST. Is there a way to do something like this:

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

这样,您发送的参数就会显示在 $ _ REQUEST

such that the parameters you send show up in the $_REQUEST variable?

推荐答案

否,没有简单的方法可以实现。 Web服务器将拆分请求字符串,并将其传递到PHP解释器,然后将其存储在 $ _ REQUEST 数组中。

No, there is no easy way to achieve that. The web server will split up the request string and pass it into the PHP interpreter, who will then store it in the $_REQUEST array.

如果您是从命令行运行的,并且想要接受类似的参数,则必须自己解析它们。命令行用于传递参数的语法与HTTP完全不同。您可能需要研究 getopt

If you run from the command line and you want to accept similar parameters, you'll have to parse them yourself. The command line has completely different syntax for passing parameters than HTTP has. You might want to look into getopt.

对于不考虑用户错误的暴力破解方法,您可以尝试以下代码段:

For a brute force approach that doesn't take user error into account, you can try this snippet:

<?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

这篇关于通过命令行调用PHP脚本时发送请求参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆