Passing GET/POST variables to php via command line?

How does one pass GET/POST variables via command line? For instance setting $getv=100 with a command line execution of test.php.

The command line doesn’t have any concept of $_GET or $_POST, because these are purely http constructs

Instead, values can be passed as command line arguments. I tend to use a format like:

php -f myScript.php -i=1 -j="value2"

Then my script will contain somethin like:


if ($_SERVER['argc'] > 1) {
	for ($commandLineIndex=1; $commandLineIndex < $_SERVER['argc']; $commandLineIndex++) {
		$commandLineArgument = explode('=', $_SERVER['argv'][$commandLineIndex]);
		$commandLineArgumentKey = array_shift($commandLineArgument);
		$commandLineArgumentValue = implode('=', $commandLineArgument);

		switch($commandLineArgumentKey) {
			case '-i' :
					if ((is_null($commandLineArgumentValue)) || (trim($commandLineArgumentValue) == '')) {
						errorTerminate('A value must be specified for : '.$_SERVER['argv'][$commandLineIndex].PHP_EOL);
					}
					$i = $commandLineArgumentValue;
					break;
			case '-j' :
					if ((is_null($commandLineArgumentValue)) || (trim($commandLineArgumentValue) == '')) {
						errorTerminate('A value must be specified for : '.$_SERVER['argv'][$commandLineIndex].PHP_EOL);
					}
					$j = $commandLineArgumentValue;
					break;
			default :
					errorTerminate('Unknown argument : '.$_SERVER['argv'][$commandLineIndex].NEWLINE.'Use -h or --help for help');
					break;
		}
	}
}

Thank you. So there’s no workaround to pass REQUEST variables via command line? Because the script this is for is a very complex pre-written script, which there’s no chance of me being able to recode to be used with the traditional CLI.

You will have to manually take the command line arguments and inject them into _REQUEST, _GET, or _POST. Or just rewrite the script anyways…

From the command line (on Linux) you can run


wget http://domain.path/to/script.php

unfortunately with this method your cli page will be acessible from the Internet same as any other page, the good thing is you can send $_REQUEST variables.

I wonder where’s the problem at all
Web-server usually provides POST/GET data to the script, so, you have no worry about it.
How do you call yor script exactly? What aplication calls it?

There is no web server involved in this at all.
The OP is calling the script from the command line

If there is no web server, there is no GET/POST.
What is OP?
In which form this OP has his POST data? a text file? a database record?

$ setenv GATEWAY_INTERFACE CGI/1.1
$ setenv REQUEST_METHOD GET
$ setenv QUERY_STRING v=100
$ setenv PATH_TRANSLATED "file.php"
$ /path/to/php-cgi file.php

http://hoohoo.ncsa.illinois.edu/cgi/interface.html