Validating Usernames with PHP

Last updated: Jun 10, 2008

Improperly validating user input has become a common scenario in security exploits these days. Recently there was a flaw in the way digg sanitized user input allowing the hacker to have his articles auto dugg. Although it took digg awhile to fix the issue, it is now resolved. The problem is that these types of attacks are becoming more common. Websites these days are rapidly evolving and changing. Programmers are pressured into producing working code in the shortest amount of time leaving room for security flaws to be left un checked.

As a PHP developer or even a guy that modifies PHP code from time to time, it is important to always validate user input. This is also called sanitizing input. This function will properly validate usernames.

The Function

function cleanUsername($string) {
     if (preg_match('/^[a-z\d_]{4,28}$/i', $string)) { 
     echo $string;
     } else {
     return false;

The following function will check to see if the username is comprised of only ‘a-z’, ‘0-9’, and ‘_’. If the username is malformed it will return false.

You can also validate telephone numbers, ip addresses, and zipcodes. Remember everything that a user can submit should be validated/sanitized. This goes for search boxes, passwords, zip codes, usernames, email addresses, comments, etc.

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