PHP Tip #2: Is_Numeric() Is A Very Useful Thing

/ PHP / by Paul Robinson / 4 Comments
This post was published back on March 13, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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

I would however prefer to use something like this:

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

Author’s gravatar

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 ^^

Reply
Author’s gravatar author

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

Reply
Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more