39

I know this could sound a little weird, but I need to pass some parameters to the $_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 installation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hades
  • 1,077
  • 3
  • 11
  • 19

3 Answers3

65

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

/* If started from the command line, 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 the command line passing your arguments:

php yourscript.php 'arg1=x&arg2=y'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Schlangi
  • 1,135
  • 1
  • 9
  • 19
  • 2
    This worked like a charm. I'm actually using Zend's version of Eclipse. I created a debug profile, as per Zend's documentation, and added PHP Script Arguments. I put your code at the top of the PHP script and viola! It parsed the arguments stored in $argv[] into the _POST array. Much grats!!! – MikeyE Sep 14 '13 at 00:26
  • Didn't work quite like that for me (W10 OS): single quotes for the $_GET/$_POST arrays had to be replaced by double quotes. – mike rodent May 24 '17 at 20:26
  • 1
    Undefined index: REQUEST_METHOD – evandrix Nov 20 '19 at 19:10
  • https://www.sitepoint.com/community/t/passing-get-post-variables-to-php-via-command-line/5572/9 – evandrix Nov 20 '19 at 19:11
  • Does not seem to work properly with filter_input(INPUT_POST,...) – Maksym Sep 22 '20 at 16:16
  • similarly doing something like this is awesome `parse_str(implode('&', array_slice($argv, 1)), $_POST);`, I found it on https://www.php.net/manual/en/features.commandline.php#108883 – Pykler Dec 06 '20 at 00:42
19

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.

mario
  • 144,265
  • 20
  • 237
  • 291
0
curl --data "name=ii" "param1=value1&param2=value2" http://test.com/sample.php
evandrix
  • 6,041
  • 4
  • 27
  • 38
user926400
  • 115
  • 1