简体   繁体   English

PHP:如何获取无密钥URL参数

[英]PHP: How to get keyless URL parameters

I would like to get the parameter in a key such as http://link.com/?parameter 我想在诸如http://link.com/?parameter的键中获取参数

I read somewhere that the key is NULL and the value would be parameter . 我在某处读到键为NULL ,值将为parameter

I tried $_GET[NULL] but it didn't seem to work. 我尝试了$_GET[NULL]但似乎没有用。

Here is my code: 这是我的代码:

if ($_GET[NULL] == "parameter") {
    echo 'Invoked parameter.';
} else {
    echo '..';
}

It just prints out .. so that means I'm not doing it right. 它只是打印出来..所以我做错了。 Can someone please show me the right way. 有人可以告诉我正确的方法吗?

There are no such things as keyless URL parameters in PHP. PHP中没有诸如无密钥URL参数之类的东西。 ?parameter is the equivalent of $_GET['parameter'] being set to an empty string. ?parameter等效于$_GET['parameter']被设置为空字符串。

Try doing var_dump($_GET) with a url like http://link.com/?parameter and see what you get. 尝试使用像http://link.com/?parameter这样的URL进行var_dump($_GET) ,看看会得到什么。

It should look something like this: 它看起来应该像这样:

array (size=1) 'parameter' => string '' (length=0)

Thus, you can test it in a couple of ways depending on your application needs: 因此,您可以根据应用程序需求以几种方式对其进行测试:

if (isset($_GET['parameter'])) {
   // do something
} else {
   // do something else
}

or 要么

// Only recommended if you're 100% sure that 'parameter' will always be in the URL.
// Otherwise this will throw an undefined index error. isset() is a more reliable test.

if ($_GET['parameter'] === '') {
   // do something
} else {
   // do something else
}

$_GET is a super global assoc array, that contains parameter => it's value pairs. $_GET是一个超级全局assoc数组,它包含parameter => it's value对。 So, parameter is a key of the array. 因此, parameter是数组的键。

For example, if your url is something like this: myweb.com/?page=load&do=magic than you $_GET is: 例如,如果您的网址是这样的: myweb.com/?page=load&do=magic不是$_GET是:

$_GET(
  [page] => load
  [do] => magic
)

If you want just to test, if parameter is in you URL as a param, you should do something like this: 如果你想只是为了测试,如果parameter是你URL作为PARAM,你应该做这样的事情:

if (isset($_GET['parameter'])
  echo "Here I am!";

You can also get the entire request_url like this 您也可以像这样获取整个request_url

echo $_SERVER['REQUEST_URI'];

To get the part after ? 要得到一部分? :

echo explode('?', $_SERVER['REQUEST_URI'])[1];

You could via array_keys() : 您可以通过array_keys()

$param = array_keys($_GET)[0];

Which would give you the name of the first querystring parameter, whether it has a value or not. 无论有没有值,这都会为您提供第一个querystring参数的名称。

You could also get all of the parameters without a value like so: 您还可以获取所有不带值的参数,例如:

$empty = [];
foreach($_GET as $key => $value)
    if(strlen($value) === 0) $empty[] = $key;

print_r($empty);

You can get the part of the URL beginning with ? 您可以获取URL中以?开头的部分? with

$_SERVER['QUERY_STRING']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM