如何将参数从命令行传递到 php-script 中的 $_POST?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5655284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:07:12  来源:igfitidea点击:

How to pass parameters from command line to $_POST in php-script?

postcommand-line-interfacephphttp-post-vars

提问by hades

I know this could sound a little weird but I need to pass some parameters to a $_POST array. Similar to the way apache does it, or any other web server.

我知道这听起来有点奇怪,但我需要将一些参数传递给 $_POST 数组。与 apache 或任何其他 Web 服务器的工作方式类似。

Unfortunately I couldn't find libapache2-mod-php5anywhere for my Ubuntu.

不幸的是,我找不到libapache2-mod-php5适合我的 Ubuntu 的任何地方。

采纳答案by mario

That's not easily doable. You can invoke the php-cgibinary and pipe a fake POST request in. But you'll need to set up a whole lot of CGI environment variables:

这并不容易做到。您可以调用php-cgi二进制文件并通过管道发送一个假的 POST 请求。但是您需要设置大量的 CGI 环境变量:

echo 'var1=123&var2=abc' | REQUEST_METHOD=POST  SCRIPT_FILENAME=script.php REDIRECT_STATUS=CGI CONTENT_TYPE=application/www-form-urlencoded php-cgi 

Note: Insufficient, doesn't work like that. But something like that...

注意:不足,不能那样工作。但类似的事情...



It's certainly easier if you just patch the script, and let it load the $_POST array from a predefined environment variable.

如果您只是修补脚本,并让它从预定义的环境变量中加载 $_POST 数组,那肯定会更容易。

$_POST = parse_url($_SERVER["_POST"]);

Then you can invoke it like _POST=var=123 php script.phpfor simplicity.

然后,_POST=var=123 php script.php为了简单起见,您可以像调用它一样调用它。

回答by Schlangi

I was searching for a solution for this and came by, because it was the first hit at Google. The second onewas somehow mor useful for me, because it has a really easy solution, if you have access to the PHP script and can change it.

我正在为此寻找解决方案并来了,因为它是谷歌的第一个热门。第二个对我来说更有用,因为它有一个非常简单的解决方案,如果您可以访问 PHP 脚本并且可以更改它。

Just insert the following lines at the beginning of your script:

只需在脚本的开头插入以下几行:

/* if started from commandline, wrap parameters to $_POST and $_GET */
if (!isset($_SERVER["HTTP_HOST"])) {
  parse_str($argv[1], $_GET);
  parse_str($argv[1], $_POST);
}

This small piece of code does the trick (you may decide if you want to use $_GET or $_POST or, like I needed it, both.
After changing your script you can call it from commandline passing your args:

这一小段代码可以解决问题(您可以决定是否要使用 $_GET 或 $_POST ,或者,就像我需要的那样,两者都使用。
更改脚本后,您可以从传递参数的命令行调用它:

php yourscript.php 'arg1=x&arg2=y'

Have fun!

玩得开心!

回答by user926400

curl --data "name=ii" "param1=value1&param2=value2" http://test.com/sample.php