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

二次信任 提交于 2019-11-27 01:18:20

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

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 = parse_url($_SERVER["_POST"]);

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

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

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:

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

Have fun!

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!