PHP Tip #2: Is_Numeric() Is A Very Useful Thing
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:
1 2 3 4 5 6 |
//$_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. 😀
Another Way To Do It
Daniel in a comment below has offered another way to write a similar thing showing the diversity of PHP. 🙂
1 2 3 |
if ( ! 0 < ( $input = (int) $_GET['input'] ) ) { // something to run if input is not valid } |
I would however prefer to use something like this:
1 2 3 4 5 |
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.
4 Comments
Daniel
Hi,
I would prefer it this way:
if ( ! 0 < ( $input = (int) $_GET[‘input’] ) ) {
// something to run if input is not valid
}
But there are many ways ^^
Veneficus Unus
Of course. That’s the great thing about PHP there are so many different ways to write the same thing it’s nearly impossible not to find a version that suits the application you are writing. 🙂
I might add your version to the post if you don’t mind. 😉
Daniel
No, thanks, I don’t mind 😉
Veneficus Unus
Thanks. 🙂