ankitweblogic logo
W e b t u t o r i a l s

Define PHP

PHP Installation


PHP Case Sensitivity

PHP Variable

PHP Echo & Print

PHP Operators

PHP Receiving Input

PHP Decision Making

PHP Loops

PHP Jumping Statement

PHP Image Gallery

PHP Arrays

PHP File Upload

PHP String Functions

PHP Math Functions

PHP Functions

PHP Variable Scope

PHP Constant Variable

PHP Superglobals

PHP Form Validation

PHP Include Statement

PHP Filter

PHP File Handling

PHP Date Functions

PHP Cookies

PHP Session

PHP Send Emails

PHP Captcha

PHP-MySQL Connectivity

PHP MySQL Select

PHP MySQL Insert

PHP MySQL Delete

PHP MySQL Update

PHP MySQL Injection

PHP Form Validation

The Data entered by the user is should be validate for security and correct input format. Proper validation of form data is important to protect your form from hackers.

Validate Form Data With PHP

Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

What is the htmlspecialchars() function?
The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or Javascript code Cross-site Scripting attacks) in forms.

Example 1: Form Validation.

PHP - Required Field

In the Above example if we want to make the "Name", "E-mail", and "Gender" fields as required so that these fields cannot be empty, than validation is to be applied.

PHP - Data Validation

Validate Name - Name field can contain capital letters, lower case letters and spaces. The preg_match() function searches a string for pattern, return true if the pattern exists, else return false.

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "Only letters and white space allowed"; 

Validate E-mail - E-mail field contain text, '@', '.'. The easiest and safest way to check an email address is to use PHP pre-define function, filter_var().

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 

Validate URL - Similarly, you can validate URL.

if (!preg_match("/\b(?:(?:https?|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  $websiteErr = "Invalid URL"; 

PHP - Keep The Values in The Form