简体   繁体   English

PHP:做所有这些检查浪费吗?

[英]PHP: is it wasteful doing all these checks?

I'am going to write an IF conditional like this: 我将要编写这样的IF条件:

if (isset($_GET['code']) && !empty($_GET['code']) && ctype_digit($_GET['code'])){
   //other code here
}

I mean, of course if I only check: 我的意思是,当然,如果我只检查:

if(ctype_digit($_GET['code'])){ }

of course $_GET['code'] exists and it is not empty, isn't it wasteful writing this conditional the first way? 当然$ _GET ['code']存在,并且它不是空的,以这种方式写条件式不是很浪费吗?

It is necessary to check if $_GET['code'] is set, before you call the function: ctype_digit() In case $_GET['code'] is not set, you would get an message similar to this: 在调用该函数之前,有必要检查$_GET['code']是否已设置: ctype_digit()如果未设置$_GET['code'] ,则会收到类似以下消息:

Notice: Undefined index: code in C:\\xampp\\htdocs\\index.php on line 2 注意:未定义的索引:第2行的C:\\ xampp \\ htdocs \\ index.php中的代码

I would say it is not wasteful to validate your input but it is if you write all that more then once. 我要说的是,验证您的输入并不是浪费,但是如果您再写一次,那就是浪费了。 I would create a method or function called isDigit() and required() and use those to check your input. 我将创建一个名为isDigit()和required()的方法或函数,并使用这些方法或函数检查您的输入。 As a code review note, you should have already validated the required fields in $_GET at the very beginning of the code if you know what is required or not. 作为代码回顾说明,如果您知道是否需要什么,则应该已经在代码的开头验证了$ _GET中的必填字段。 (Actually I wouldn't even call $_GET directly I would have it handled in an Object that validates and sanitizes data from the outside.) (实际上,我什至不直接调用$ _GET,而是让它在从外部验证和清除数据的对象中进行处理。)

It depends on your error handling. 这取决于您的错误处理。 If you will omit the first check and element with key 'code' won't exist in $_GET array, E_NOTICE will be raised. 如果您省略第一个检查,并且$_GET数组中不存在带有键“代码”的元素,则将引发E_NOTICE And, for example, if your server responses with 500 error in this cases, user will see a nasty 500 page. 并且,例如,如果在这种情况下服务器响应500错误,则用户将看到一个讨厌的500页面。 If you error reporting is disabled for E_NOTICE you can omit the fist and the second checks. 如果您为E_NOTICE禁用了错误报告功能,则可以省略第一拳和第二拳。

使用isset()ctype_digit()应该没问题。

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

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