简体   繁体   English

在读取/使用变量之前,是否总是需要检查是否设置了post和get变量?

[英]Do we always need to check if post and get variables are set before reading/using them?

Consider the following example: 考虑以下示例:

if ( isset($_POST['type']) && 'page' == $_POST['type'] )
    return;

Do we need the isset($_POST['type']) check? 我们需要isset($_POST['type'])检查吗?

From what I've seen so far the following has the seem result: 从目前为止我所看到的似乎是以下结果:

if ( 'page' == $_POST['type'] )
    return;

Or can this cause problems in certain situations? 还是在某些情况下会引起问题?

Using " isset " is right approach otherwise it will throw warning: "index type is undefined". 使用“ isset ”是正确的方法,否则将引发警告:“索引类型未定义”。 Also it checks whether array is empty or not. 它还检查数组是否为空。

isset() function will serve the replacement of two functions isset()函数将用于替换两个函数

if(!empty(your_array) && array_key_exists('type',$POST['type']))

So use this check to avoid further complications 因此,请使用此检查以避免进一步的并发症

This can cause problems like error notice: PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" 这可能会导致出现错误通知之类的问题: PHP:“通知:未定义的变量”,“通知:未定义的索引”和“通知:未定义的偏移量”

You can use array_key_exists instead of isset . 您可以使用array_key_exists代替isset array_key_exists method will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null array_key_exists方法肯定会告诉您数组中是否存在键,而isset仅在键/变量存在且不为null时返回true

There is another important difference. 还有另一个重要区别。 isset doesn't complain when $x does not exist, while array_key_exists does. 当$ x不存在时, isset不会抱怨,而array_key_exists则不会。

$x = [
    'key1' => 'abcd',
    'key2' =>  null
];

isset($x['key1']);             // true
array_key_exists('key1', $x);  // true

isset($x['key2']);             // false
array_key_exists('key2', $x);  // true

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

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