The second in my series of PHP tips is to do with the extremely handy is_numeric(). When allowing user input it’s extremely important to check the input for attacks. The most common piece of information handed to MySQL is an ID, but novice coders can get confused with how to check the input. The main [...]

The second in my series of PHP tips is to do with the extremely handy is_numeric(). When allowing user input it’s extremely important to check the input for attacks. The most common piece of information handed to MySQL is an ID, but novice coders can get confused with how to check the input. The main problem is that you only want a number, but you can’t check for an integer since it will be a string. That’s where is_numeric() comes to the rescue. Just check to see if the user input is_numeric() & if it is do whatever you want. If we need an integer instead of a string we can use type casting. Here’s an example:

//$_GET['input'] is equal to the string 3.
if(is_numeric($_GET['input'])) {
  (int) $_GET['input'] = $input;
} else {
  //Something to run if input is not valid.
}

Simplez. :D

Another Way To Do It

Daniel in a comment below has offered another way to write a similar thing showing the diversity of PHP. :)

if ( ! 0 < ( $input = (int) $_GET['input'] ) ) {
  // something to run if input is not valid
}

I would however prefer to use something like this:

if ( ! 0 > ( $input = (int) $_GET['input'] ) ) {
  // something to run if input is not valid
} else {
  //something to run if successful
}

Since a string converted to an integer will always produce 0 that will detect invalid input without using is_numeric() for the most part anyway. Just bare in mind it will also mark 0 as invalid.