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?
using isset()
and ctype_digit()
should be fine.
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
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.
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.)