Open Source PHP Data Validation Class

I have created a PHP5 class that handles all POST and GET variables. It performs almost all of the validations functions you could need. In addition, it makes accessing the variables very convenient.

Download here.
Version 1.0

How To use:
First, include the class and initiate it:

<?php
include("validation.class.php");
$validation = new Validation;
?>

Optionally, you can use new Validation(false) to not parse all input data through the xss filter. This is not recommended.

Available functions are:

  • xss($string)
  • email($string)
  • phone($string)
  • url($string)
  • db_prep($string)

All of the above functions return a boolean value with the exception of xss() and db_prep(). Those two return a modified version of $string.

Here is an example of form validation:

<?php
$db_user = "";
$db_pass = "";
$db_serv = "";
$db_name = "";
include("../database/database.class.php");
$db = new Database($db_user,$db_pass,$db_serv,true);
if(!$db){die($db->getErrorMessage());}

include("validation.class.php");
$validation = new Validation;

echo "SELECT * FROM users WHERE user='".$validation->db_prep($validation->database_input)."'";
echo "<br>";

if($validation->email($validation->email)) echo "valid email";
else echo "not valid email";
echo "<br>";

if($validation->phone($validation->phone)) echo "valid phone";
else echo "not valid phone";
echo "<br>";

if($validation->url($validation->url)) echo "valid url";
else echo "not valid url";
echo "<br>";
?>
<form action="test.php" method="post">
	<p>database input: <input type="text" name="database_input" id="database_input" value="<?=$validation->database_input;?>" /></p>
    <p>email: <input type="text" name="email" id="email" value="<?=$validation->email;?>" /></p>
    <p>phone: <input type="text" name="phone" id="phone" value="<?=$validation->phone;?>" /></p>
    <p>url: <input type="text" name="url" id="url" value="<?=$validation->url;?>" /></p>
    <p><input type="submit" name="test" id="dtest" value="Test" /></p>
</form>

A demo of the above test can be found here.

As you can see from the example above, instead of calling $_GET['username'], you can now call $validation->username without worrying about the data being ‘dirty’.

If you need help using this class, post a comment and I will gladly help you out. Also remember that this class is licensed under the Buy Me Dew License.

2 Responses to “Open Source PHP Data Validation Class”

  1. DPush Says:

    Hi!
    What are u using for SKIPPED_VARS array? and its part in constructor.
    Thx.

  2. dawnerd Says:

    skipped_vars holds all vars that may conflict with portions of the script. There’s really no use to it other than being a backup of the data should there be any issues.

Leave a Reply






Copyright 2008 Troy Whiteley & OjaiSoft

CSS | PHP | XHTML/HTML | JavaScript | Featured Sites

Home | Labs | License | RSS | Log in