Home arrow PHP arrow Page 4 - Advanced PHP Form Input Validation to Check User Inputs

Validating Alphanumeric, Numeric and Alphabetic Input - PHP

PHP form input validation is what separates amateur and professional PHP developers. A professional PHP developer validates data for both security and correctness of the data entered. Keep reading to learn how to validate user input to your forms.

TABLE OF CONTENTS:
  1. Advanced PHP Form Input Validation to Check User Inputs
  2. Validating Email Addresses
  3. Validating Domains for Email Addresses
  4. Validating Alphanumeric, Numeric and Alphabetic Input
By: Codex-M
Rating: starstarstarstarstar / 15
June 01, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Alphanumeric input is common in web forms. Most usernames and passwords are formatted using alphanumeric data types.

Luckily, PHP provides a function for checking alphanumeric characters. This function is called:

ctype_alnum($stringtotest)

It is important to note that security issues such as MySQL injection can only be corrected with the mysql_real_escape_string(stripslashes($stringtotest)) function.

IMPORTANT: Before inputting or querying a MySQL database, it is highly advisable to use the above escape function for your safety.

Also, validating empty fields can be done using:

if (!isset($_POST['email']) || trim($_POST['email']) == "")

as illustrated in the PHP email validation script. However, there are a lot of ways to do this, such as the empty() function, which will be illustrated below.

Numeric input only can be validated by: ctype_digit($stringtotest) and lastly, alphabet characters (alphabet input only) can be validated using: ctype_alpha($stringtotest)

Below is a sample script illustrating the above PHP data type validation function in action. It also prevents MySQL injection and reports all validation errors at once:

<?php

//The script will test various datatypes such as alphanumeric, numeric and alphabet characters

//This also checks if the data entered is not blank and prevent mysql injection.

//If the data entered is clean it will be save to the MySQL database

//connect to MySQL database

$username = "root";

$password = "xxxxx";

$hostname = "localhost";

$table = "datatypevalidation";

$database = "email";

//connection to the database

$dbhandle = mysql_connect($hostname, $username, $password)

or die("Unable to connect to MySQL");

//select a database to work with

$selected = mysql_select_db($database,$dbhandle)

or die("Could not select $database");

if (!$_POST['submit'])

{

//form not submitted

?>

<form action="<?php echo $SERVER['PHP_SELF']; ?>"

method="post">

Username(alphabet characters only e.g John):

<br />

<input type="text" name="username" size="50">

<br /><br />

Password (alphanumeric characters only e.g John458):

<br />

<input type="text" name="password" size="50">

<br /><br />

Birthday (numeric characters only e.g 12011986 for December 1, 1986):

<br />

<input type="text" name="birthday" size="50">

<br /><br />

<input type="submit" name="submit" value="Submit and validate data entered">

</form>

<?php

}

else

{

//array to store the error messages

$mistakes = array();

//validate username field

$username = trim($_POST['username']);

If (empty($username) || (!(ctype_alpha($username))))

{

$mistakes[] = 'Your username is either empty or Enter only ALPHABET characters.';

}

else

{

//accept username entry and sanitize it

$username = mysql_real_escape_string(stripslashes($username));

}

//validate password field

$password = trim($_POST['password']);

If (empty($password) || (!(ctype_alnum($password))))

{

$mistakes[] = 'Your password is either empty or Enter only ALPHANUMERIC characters ';

}

else

{

//accept password entry and sanitize it

$password = mysql_real_escape_string(stripslashes($password));

}

//validate birthday field

$birthday = trim($_POST['birthday']);

If (empty($birthday) || (!(ctype_digit($birthday))))

{

$mistakes[] ='Your birthday is either empty or Enter only NUMERIC characters';

}

else

{

//accept birthday data and sanitize it

$birthday = mysql_real_escape_string(stripslashes($birthday));

}

if (sizeof($mistakes) > 0)

{

echo "<ul>";

foreach ($mistakes as $errors)

{

echo "<li>$errors</li>";

}

echo "</ul>";

echo '<br />';

echo "Press back button to CORRECT the entry";

mysql_close($dbhandle);

die ();

}

else

{

//save to database

mysql_query("INSERT INTO `datatypevalidation` (`username`,`password`,`birthday`) VALUES('$username','$password','$birthday')")

or die(mysql_error());

echo "SUCCESS! Thanks for the data you entered, it is already save to the database";

echo '<br />';

echo "This is your copy:";

echo '<br />';

echo '<br />';

echo "Username:".' '.$username;

echo '<br />';

echo "Password:".' '.$password;

echo '<br />';

echo "Birthday:".' '.$birthday;

echo '<br />';

echo '<br />';

echo '<a href="http://localhost/datatypevalidation.php">Try entering another sets of data</a>';

mysql_close($dbhandle);

}

}

?>

The great thing about this script is that it will validate each field against the defined standard (if it is alphabetic, alphanumeric or numeric entry), and then display all validation errors as a list to inform the user what has been entered incorrectly.

In this way, the form is more user-friendly, and at the same time, it ensures that all data entered will be in the correct format and MySQL injection will be prevented.

If you would like to download the script, refer to the author website: http://www.php-developer.org/ . Thanks.



 
 
>>> More PHP Articles          >>> More By Codex-M
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: