Form Validation (Basic Server-Side Validation)
Form validation ensures that the data entered by the user is correct, complete,
and safe before processing it. In server-side
validation, PHP checks the submitted data after it reaches the server,
making it more secure than client-side validation.
Why
Server-Side Validation is Important
·
Prevents invalid or
incomplete data from being stored in the database.
·
Protects against malicious
input (e.g., XSS, SQL injection).
·
Works even if JavaScript is
disabled in the browser.
Example:
Basic Form with Validation
<?php
$name =
$email =
"";
$nameErr =
$emailErr =
"";
if (
$_SERVER[
"REQUEST_METHOD"] ==
"POST") {
// Validate name
if (
empty(
$_POST[
"name"])) {
$nameErr =
"Name is required";
}
else {
$name =
htmlspecialchars(
$_POST[
"name"]);
}
// Validate email
if (
empty(
$_POST[
"email"])) {
$emailErr =
"Email is required";
}
elseif (!
filter_var(
$_POST[
"email"], FILTER_VALIDATE_EMAIL)) {
$emailErr =
"Invalid email format";
}
else {
$email =
htmlspecialchars(
$_POST[
"email"]);
}
}
?>
HTML
Form:
<form method=
"post" action=
"">
Name: <input type=
"text" name=
"name" value=
"<?php echo $name; ?>">
<span style=
"color:red;">
<?php
echo
$nameErr;
?></span>
<br><br>
Email: <input type=
"text" name=
"email" value=
"<?php echo $email; ?>">
<span style=
"color:red;">
<?php
echo
$emailErr;
?></span>
<br><br>
<input type=
"submit" value=
"Submit">
</form>
How It
Works
1.
The form sends data to the same PHP page when submitted.
2.
PHP checks if each field is empty
or invalid.
3.
If errors are found, they are
displayed next to the respective input fields.
4.
Data is sanitized using htmlspecialchars()
to prevent malicious scripts.
5.
The form retains previously
entered values to improve the user experience.
Key
Validation Functions in PHP
·
empty()
→ Checks if
a field is empty.
·
filter_var($var, FILTER_VALIDATE_EMAIL)
→ Validates email format.
·
htmlspecialchars()
→
Escapes HTML special characters to prevent XSS.
·
strlen()
→ Checks
length of strings.