Page Stats
Visitor: 377
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 data from attackers/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 PHP empty function is use to validate field.
Example 2: empty function, to make text field as required.
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 (filter_var($url, FILTER_VALIDATE_URL)) { echo("$url is a valid URL"); } else { echo("$url is not a valid URL"); }OR
if (!preg_match("/\b(?:(?:https?|http):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; }
Example 3: Form with validation.
PHP - Keep The Values in The Form
Example 4: Form with validation do not reset the form values.