Validating your PHP Input

In this world of bad guys and hackers and crackers, us developers have to be on our guard against all sorts of stuff that tries to break our websites. Validating input using JavaScript alone is not sufficient to gurad against the baddies as it can be worked around by building their own custom forms to interact with your site and/or disabling JavaScript.

What this means is that every piece of data you accept from a user should be validated against a set of rules for that datatype.

Some general validation rules

If it’s a text string, does it contain any less than or greater than brackets?

If it’s a date, are it’s day, monthy, year parts valid numbers?

If it’s a credit card number, is there an online number validation algorithm you can use to verify it?

Regular Expressions in PHP

In order to validate your user-input, you’ll generally find yourself resorting to regular expressions. In PHP there are two options.ereg and preg. ereg is older, less sophisticated and somewhat slower than it’s younger brother. My preference is to use the preg options even though they’re a little more complicated, the end results is betterer(sic).

An example of using preg to validate a date:

$month = $_GET['cardmonth'];
$year = $_GET['cardyear'];
if (!preg_match(“/^[0-9]{1,2}$/”, $month)) die(“Invalid month, please re-enter.”);
if (!preg_match(“/^[0-9]{4}$/”, $year)) die(“Invalid year, please re-enter.”);

An online manual is available from the main php website at http://www.php.net/manual/en/ref.pcre.php

And some lessons explicitly on how to use the preg function is available here http://www.php.net/manual/en/function.preg-match.php

  • Share/Bookmark

One Response to “Validating your PHP Input”

  1. w3cvalidation @ April 30th, 2010

    Nice information, I really appreciate the way you presented.Thanks for sharing..

Leave a Reply



Spam protection by WP Captcha-Free