php如何解析url参数?

How php parse the url parameter?

我有一个url

www.example.com?para1=&para2=2

我试着判断para1和para2 ;

isset($_GET['para1'] )       // true
 isset($_GET['para2'])       //true;
 isset($_GET['para3'])       // false

我认为 isset($_GET['para1'] ) 是错误的,但似乎不是。

我的问题:

为什么isset($_GET['para1'] )是true.How它解析php中的url?

isset() returns 正确,因为它已在您的请求中设置但为空字符串。

您想使用 !empty().

根据您的要求www.example.com?para1=&para2=2

para1=nullpara2=2

所以:

if (!empty($_GET['para1'])) {}

isset($var) 将 return true 因为参数存在于 url 中,如果您检查它的值,您会发现一个空字符串 ""

您还可以使用 empty($var) 函数来测试空值,只需注意空值将 return 为真,例如:

0, "", [], null, false ---> empty() return true

否则它将return错误

我通常会获取参数,如果它们不存在,我会使用像这样的函数给它们默认值:

function get($item, $type = 'string', $default = null, $escape = true)
{
   if(!isset($_GET[$item])) {
     return $default;
   }

   $output = $_GET[$item];

   settype($output, $type);

   return $escape ? htmlspecialchars(trim($output)) : $output;
}

echo get('para1');
echo get('name', 'string', '');
echo get('admin', 'bool', false);

尝试编辑你喜欢的功能,希望对你有所帮助

isset($var) returns true 如果定义了变量,不管值是多少(null除外)。在您的情况下,它已定义但包含一个空字符串。
如果未定义变量并测试实际内容,您会希望使用 empty($var) 不会引发异常。

Documentation

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.

这里很多人都说 $_GET['para1'] 的值是 null 但事实并非如此。 a comment on the php.net $_GET docs 提供了一个有用的脚本来测试它。

给定 URL:http://www.example.com?a

您可以使用这个脚本来测试结果:

<?php
print_r($_GET);
if($_GET["a"] === "") echo "a is an empty string\n";
if($_GET["a"] === false) echo "a is false\n";
if($_GET["a"] === null) echo "a is null\n";
if(isset($_GET["a"])) echo "a is set\n";
if(!empty($_GET["a"])) echo "a is not empty";
?>
</pre>

输出将是:

a is an empty string
a is set

之所以如此,是因为没有值的键实际上是一个空字符串 不是 null

所以直接回答你的问题:

虽然看起来 para1 没有设置值,但实际上有。该值为空字符串 ("")。尽管这个值是假的,但它仍然是一个值,因此 isset() return 是真的。您可以在空字符串上使用 !empty() 到 return false。查看 isset() empty()is_null() here.

的比较

以下是一些可以帮助您实现所需的提示:

  • 检查是否设置了变量,

    isset($var)
    
  • 检查var是否设置且不为空,

    !empty($var)
    
  • 要检查 var 是否不为空且不为空格,

    !empty($var) && !trim($var) == false
    

该值存在于$_GET数组中,但他的值为null,函数isset只评估该值是否初始化,不评估该值是否为真。

如果你想知道这个值是否为真,你可以将数组索引与==运算符进行比较,像这样var_dump($_GET['para1'] == true)