Using PHP to Accept Only Numbers From User Input

Last updated: May 20, 2008

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!

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Get notified on new posts or other things I'm working on

Share: