简体   繁体   中英

PHP: is it wasteful doing all these checks?

I'am going to write an IF conditional like this:

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?

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:

Notice: Undefined index: code in C:\\xampp\\htdocs\\index.php on line 2

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. 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. (Actually I wouldn't even call $_GET directly I would have it handled in an Object that validates and sanitizes data from the outside.)

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. And, for example, if your server responses with 500 error in this cases, user will see a nasty 500 page. If you error reporting is disabled for E_NOTICE you can omit the fist and the second checks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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