Using PHP to Accept Only Numbers From User Input

Almost all website attacks are caused by developers failing to sanitize user input. The standard security practice for handling user input is to “whitelist” it. Whitelisting converts ANY user input into the expected data type. For example if the input you are expecting is supposed to be a zipcode you need to create a script that will only except 5 numerical digits (9 if you support the +4 zipcodes). The more defined you can make your whitelist the more secure your script will be. If the user’s input cannot be converted to the whitelisted data type, in our case 5 numerical digits, then you return an error, “invalid zipcode”.

Why sanitize input

 
If you do not sanitize user input you run in the risk of cross site scripting (XSS) attacks, SQL injection, and other attacks. We as developers often write code expecting a certain type of user input not realizing that the user may not always give us what we expect. Since we have no idea what the user might send we can’t trust them (sorry). For best security practices we should always assume the user could be an attacker.

Another benefit of sanitizing the code is correcting typos. Maybe someone just typed in ‘90210p‘ as a zipcode on accident or maybe they left a space at the end. Instead of wasting the user’s time redirecting back and spitting out an error message, “invalid zipcode” you could strip off the ‘p‘ and run the script normally. Although we can’t trust our users we shouldn’t make it more difficult for them.

The Function

 
Here is a function I created that takes any string, finds all numbers and drops the rest.

<?php
function sanitizeInput($string) { return ereg_replace("[^0-9]", "", $string); }

echo sanitizeInput('blah123');
?>

The above example would output, ‘123‘.

Even if the user input is not going to be used in an SQL query, you should always sanitize the input!




4 Responses to "Using PHP to Accept Only Numbers From User Input"
  1. David Walsh on May 22nd, 2008

    Awesome function. For the sake of briefness in code, I would simply do:

    function sanitizeInput($string) { return ereg(….); }

    Since this isn’t a function that you’d need to modify ever again, I like shortening it as much as possible.

    That’s just me being picky though.

  2. Mark Sanborn on May 22nd, 2008

    @David

    Thanks for the suggestion. I like optimized code as well and I am going to update the post to make it shorter. :)

  3. [...] Last week I wrote about Validating Telephone Numbers With PHP and Using PHP to Accept Only Numbers From User Input. [...]

  4. Sending Post Data With cURL on August 7th, 2008

    [...] course if you are doing any MySQL data exchanges or anything else of that nature you will want to sanatize the data before using [...]

Leave a reply