Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Explaination of (int)/intval()

(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.

Cons:

  1. It does not validate the input as an integer, it only typecasts it to an integer regardless of passed type.
  2. 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).
  3. 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.
  4. 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.

Pros

  1. 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.
  2. Faster

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." 

http://php.net/manual/en/language.types.integer.php#language.types.integer.casting.from-other

** 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment