(int) Typecast / intval()
Typecasting in PHP is a way to force a value into a format such as an integer without condition or recourse. This means that typecasting with (int) is a form of sanitization but not validation and thus does not provide a message when the value passed is not the proper type.
- It does not validate the input as an integer, it only typecasts it to an integer regardless of passed type.
- Malformed IDs are “allowed” in that they are converted to 0 (int) value and the script continues as if you requested an object with an ID of 0. (see php docs warnings below).
- Only time (int) typecasting throws an exception is when a class is typecast as an (int) and since WordPress does not inherently catch exceptions for validating it is relatively useless.
- The program does not know that a malformed ID was passed to the request until after the database query fails or returns an unexpected result. **early detection was cited as a reason for doing this early and throughout the codebase instead of sanitizing just before post injection, however the implications of an unconditional typecast seem to not have been taken into account.
- Sanitizes input to a integer which is the only ‘type’ an ID can take in the database. Anything other than an integer passed to the database as an ID would be unnecessary.
PHP Docs warnings re: int()
"WARNING Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results. "
"Caution The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice."
** A note on intval() : intval() is a function that typecasts the value passed as (int). It also allows for conversion when passing a second optional parameter as a ‘base’ for the conversation. intval() has a slight benefit over (int) in that as a function, it can be passed as a parameter in functions like arrap_map() for sanitization purposes.