How to pass query string parameters to the PHP binary?

不羁的心 提交于 2020-01-23 08:14:07

问题


I am developing a webserver that invokes the PHP binary (via CGI) to process a script.

Here's the problem:

The PHP script isn't picking up the command line parameters. For example, if the client requests path/to/file.php?test=value, the $_GET array is empty.

I have tried passing the parameters in an environment variable (QUERY_STRING), but they still don't show up.

How can I pass query string parameters to a PHP application?


回答1:


There are various SAPIs for PHP. One of them is cli SAPI which apparently is what you're using, cli SAPI wouldn't populate $_GET, $_POST ... because it's for command line scripting.

In your case you need PHP cgi SAPI. (e.g., You need to replace php with php-cgi[1] in your shebang)

[1] In most distribuitons it's called php-cgi, if you compile PHP yourself you need to enable cgi.




回答2:


Are you talking about command line parameters or $_GET parameters? Those are not the same.

When using a webbrowser, $_GET is used. But if you're passing command line arguments like /path/to/file.php arg1 arg2, then you have to use $argv (and $argc contains the length of elements).

$argv[0] always contains the running file, in this example /path/to/file.php.
$argv[1] is arg1 in this case and $argv[2] is arg2. So $argc contain 3.

Helpful resources:

  • http://php.net/manual/en/reserved.variables.argv.php
  • http://php.net/manual/en/features.commandline.php
  • http://php.net/manual/en/features.commandline.differences.php



回答3:


As mentioned in Don’t call me DOM » Testing CGI scripts with QUERY_STRING, in PHP, you may have to use parse_str to parse environment variables passed via cli mode - example in Linux terminal:

$ QUERY_STRING="aa=bb&cc=dd" php -r 'parse_str(getenv("QUERY_STRING"),$_GET); print_r($_GET);'
Array
(
    [aa] => bb
    [cc] => dd
)



回答4:


-- Option 1: php-cgi --

Use 'php-cgi' in place of 'php' to run your script. This is the simplest way as you won't need to specially modify your php code to work with it:

php-cgi -f /my/script/file.php a=1 b=2 c=3

-- Option 2: if you have a web server --

If the php file is on a web server you can use 'wget' on the command line:

wget 'http://localhost/my/script/file.php?a=1&b=2&c=3'

OR:

wget -q -O - "http://localhost/my/script/file.php?a=1&b=2&c=3"

-- Accessing the variables in php --

In both option 1 & 2 you access these parameters like this:

$a = $_GET["a"];
$b = $_GET["b"];
$c = $_GET["c"];


来源:https://stackoverflow.com/questions/3848901/how-to-pass-query-string-parameters-to-the-php-binary

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