FORM VALIDATION IN
PHP
Form validation in PHP is crucial for several reasons:
[Link] Integrity: It ensures that the data submitted by users is
accurate, consistent, and meets the expected format. This prevents
incorrect or invalid data from being stored in your database, which
could lead to errors or corrupt data.
[Link]: Proper form validation helps protect your application
from malicious attacks like SQL injection, cross-site scripting (XSS),
and other types of code injection attacks. Without validation,
attackers could potentially send harmful data that could
compromise your system.
[Link] Experience: Validating form inputs on the client side (using
JavaScript) and the server side (using PHP) helps provide a better
user experience. It allows you to give immediate feedback to users
if they make a mistake, rather than waiting for the form submission
to process and return an error.
4. Preventing Unintended Actions: It helps prevent unintended
actions or submissions. For example, if your form has a field for a
[Link] with Business Rules: Many applications have
specific rules or requirements for the data they accept. For
instance, a registration form may require a valid email address, a
password of a certain length, or specific types of characters.
Form validation enforces these rules.
[Link] Data Storage: Validating form inputs helps
ensure that the data stored in your database is consistent. This is
important for generating reports, performing searches, and other
operations that rely on accurate and structured data.
[Link] Handling: Form validation provides a structured way to
handle errors. It allows you to display meaningful error messages
to users, helping them understand what went wrong and how to
correct it.
The validation rules for the form are as follows:
Field Validation Rules
Name Required. + Must only contain letters and
whitespace
E-mail Required. + Must contain a valid email
address (with @ and .)
Website Optional. If present, it must contain a valid
URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
Text Fields
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></
textarea>
Radio Buttons
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
The Form Element
<form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The $_SERVER["PHP_SELF"] is a super global variable that returns
the filename of the currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to
the page itself, instead of jumping to a different page. This way,
the user will get error messages on the same page as the form.
The htmlspecialchars() function converts special characters to
HTML entities. This means that it will replace HTML characters like
< and > with < and >. This prevents attackers from exploiting
the code by injecting HTML or JavaScript code (Cross-site Scripting
attacks) in forms.
Cross-site scripting (XSS) is a type of computer security
vulnerability typically found in Web applications. XSS
enables attackers to inject client-side script into Web
pages viewed by other users.
A hacker can redirect the user to a file on another server,
and that file can hold malicious code that can alter the
global variables or submit the form to another address to
save the user data, for example.
$_SERVER["PHP_SELF"] exploits can be avoided by using the
htmlspecialchars() function.
The form code should look like this:
<form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
We will also do two more things when the user submits the
form:
Strip unnecessary characters (extra space, tab, newline)
PHP - Validate Name
The preg_match() function searches a string for pattern,
returning true if the pattern exists, and false otherwise.
This function is used for performing a regular expression
match
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
t's used to check if the $name variable matches the specified regular
expression pattern
^: Matches the start of a string.
[a-zA-Z-' ]:This is a character class that matches any letter (both
uppercase and lowercase), hyphens, apostrophes and spaces.
*:Matches zero or more occurrences of the preceding pattern.
PHP - Validate E-mail
The easiest and safest way to check whether an email address is
well-formed is to use PHP's filter_var() function.
filter_var() is a function in PHP used to filter a variable with a
specified filter
FILTER_VALIDATE_EMAIL is a predefined constant specifically
designed to validate email addresses. It only verifies the syntax of the
email address.
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
.
PHP - Validate URL
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
/\b:This is a word boundary anchor. It matches the position between a word character
(as \w) and a non-word character. It ensures that the URL is a separate word or
surrounded by non-word characters.
(?:(?:https?|ftp):\/\/|www\.) :This part of the pattern matches the protocol part of the
URL. It looks for either http,htttps,ftp followed by :// OR it looks for www. The ?:is used
for non-capturing groups, meaning that the matched text won't be captured as a
separate group.
[-a-z0-9+&@#\/%?=~_|!:,.;]* :This part matches the path and query string of the URL.
It allows for various characters that are commonly used in URLs.
[-a-z0-9+&@#\/%=~_|] :This part matches the last character in the URL (e.g., a
filename or an anchor).
/I :flag makes the pattern case-insensitive, so it will match both upper and lower case
letters
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email,
FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required
field</span></p>
<form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"
]);?>">
Name: <input type="text" name="name" value=
"<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?
></span>
E-mail: <input type="text" name="email"
value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?
></span>
<br><br>
Website: <input type="text" name="website"
value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?
></span>
<br><br>
Comment: <textarea name="comment"
rows="5" cols="40"><?php echo
$comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if
(isset($gender) && $gender=="female") echo
"checked";?> value="female">Female
<input type="radio" name="gender" <?php if
(isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender" <?php if
(isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;