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

hades picture hades · Apr 13, 2011 · Viewed 38.3k times · Source

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.

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

Answer

Schlangi picture Schlangi · Jul 18, 2013

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!