pTutorial

New way to learn PHP

PHP 5 form validation

What is form validation?

Form validation is a technique to protect your data from the hacker and spammer or you can say validation is important to protect your data from hacker and spammer.

In other word technique to check data before submission of the form, if form data in not proper error message will occur and data would not sent.


Types of form validation

  • Server side validation
  • Client side validation

Client side validation

As the name says, client side validation is performed on the client side by using different client side scripting language like Java script. Client side validation is faster, simpler and server friendly than server side script language. But easily breakable.


Server side validation

As the name says, server side validation is performed on the server side by using different server side scripting language like PHP. Server side validation is more secure than client side validation. Not breakable in any case.


Need of form validation

  • Prevent the unauthorised access.
  • Prevent unwanted data.
  • Increase the security.

Simple Html form that contain text field, radio button and submit button

Name:
Roll NO:
Branch:
Gender: Male Female

HTML code



<html>
<body>

<form action="process.php" method="post">
<table width="200">
<tr>
<td>Name: </td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Roll NO:</td>
<td><input type="text" name="roll"></td>

</tr>
<tr>
<td>Branch:</td>
<td><input type="text" name="branch"></td>

</tr>
<tr>
<td>Gender:</td>
<td>Male<input type="radio" name="gen" value="male"> 
Female<input type="radio" name="gen" value="female"></td>

</tr>

<tr>
<td><input type="submit" name="sub" value="send"></td>
<td><input type="reset" name="reset"></td>
</tr>
</table>
</form>

</body>
</html>


PHP script for process the form data

   
//process.php
<?php

if(isset( $_POST['sub']))
{
$a=check($_POST["name"]);
$b=check($_POST["roll"]);
$c=check($_POST["branch"]);
$d=check($_POST["gen"]);

echo "Name of student : ".$a."<br>";
echo "Roll of student  ".$b."<br>";
echo "Branch of student = ".$c."<br>";
echo "Gender of student = ".$d."<br>";		

}



function check( $value )
{
$temp = trim($value);
$temp = htmlspecialchars($value);
return $temp; //security validate
}

?>    

htmlspecialchars() is used to convert some special character in string with special meaning in HTML to their safe HTML entity. e.g. & will be converted to "&amp;". htmlspecialchars function prevents the security breach.

Method is the most important thing at the time form processing. Always use the POST method for secure data.

trim function is used to remove the special character (like \n, \t and \r) from leading and trailing.


QUOTES OF THE DAY

Wicked men obey from fear, good men from love

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER