Best Practices
Server-Side validation with PHP
1. Basic Required Field Validation
Assignment: Create a form with a text field for the user's name. The name is required, and if it is left blank, display an error message.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['name'])) {
echo "Name is required.";
} else {
echo "Name: " . htmlspecialchars($_POST['name']);
}
}
?>
<form method="POST">
Name: <input type="text" name="name"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use empty() to check if the name field is empty.
- If empty, an error message is displayed, otherwise, the value is sanitized using htmlspecialchars() and displayed.
2. Email Format Validation
Assignment: Create a form with an email field. Validate if the input is a valid email format.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
} else {
echo "Valid email: " . htmlspecialchars($email);
}
}
?>
<form method="POST">
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use filter_var() with the FILTER_VALIDATE_EMAIL filter to check if the email format is valid.
3. Number Validation
Assignment: Create a form where the user enters their age. The age should be numeric.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$age = $_POST['age'];
if (!is_numeric($age)) {
echo "Age must be a number.";
} else {
echo "Age: " . htmlspecialchars($age);
}
}
?>
<form method="POST">
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use is_numeric() to check if the input is a valid number.
4. String Length Validation
Assignment: Create a form where the user enters a password. The password should be between 8 and 16 characters long.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$password = $_POST['password'];
if (strlen($password) < 8 || strlen($password) > 16) {
echo "Password must be between 8 and 16 characters.";
} else {
echo "Password: " . htmlspecialchars($password);
}
}
?>
<form method="POST">
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use strlen() to check the length of the password.
5. Date Format Validation
Assignment: Create a form to input a date in YYYY-MM-DD format. Validate if the date is in the correct format.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$date = $_POST['date'];
$dateObj = DateTime::createFromFormat('Y-m-d', $date);
if (!$dateObj || $dateObj->format('Y-m-d') !== $date) {
echo "Invalid date format.";
} else {
echo "Date: " . htmlspecialchars($date);
}
}
?>
<form method="POST">
Date: <input type="text" name="date"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use DateTime::createFromFormat() to check if the date is in YYYY-MM-DD format.
6. Phone Number Validation
Assignment: Create a form where the user enters their phone number. The phone number must be exactly 10 digits.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$phone = $_POST['phone'];
if (!preg_match("/^[0-9]{10}$/", $phone)) {
echo "Phone number must be exactly 10 digits.";
} else {
echo "Phone: " . htmlspecialchars($phone);
}
}
?>
<form method="POST">
Phone: <input type="text" name="phone"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use preg_match() with a regex pattern to ensure the phone number consists of exactly 10 digits.
7. Username Validation
Assignment: Validate that the username contains only letters, numbers, and underscores.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
if (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
echo "Invalid username. Only letters, numbers, and underscores are allowed.";
} else {
echo "Username: " . htmlspecialchars($username);
}
}
?>
<form method="POST">
Username: <input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use preg_match() with a regular expression to ensure the username only contains valid characters.
8. Multiple Fields Validation (Required)
Assignment: Validate a form with three fields: name, email, and age. Ensure all fields are filled in.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
if (empty($name) || empty($email) || empty($age)) {
echo "All fields are required.";
} else {
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
echo "Age: " . htmlspecialchars($age) . "<br>";
}
}
?>
<form method="POST">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We check if any of the fields are empty using empty(). If they are, an error message is displayed.
9. Confirm Password Validation
Assignment: Create a form with a password and confirm password field. The passwords must match.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
if ($password !== $confirmPassword) {
echo "Passwords do not match.";
} else {
echo "Passwords match.";
}
}
?>
<form method="POST">
Password: <input type="password" name="password"><br>
Confirm Password: <input type="password" name="confirmPassword"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We check if the two password fields match. If they don’t, an error message is displayed.
10. Dropdown Validation
Assignment: Create a form with a dropdown to select the user's country. Ensure a country is selected.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$country = $_POST['country'];
if ($country == "none") {
echo "Please select a country.";
} else {
echo "Selected country: " . htmlspecialchars($country);
}
}
?>
<form method="POST">
Country:
<select name="country">
<option value="none">Select a country</option>
<option value="US">United States</option>
<option value="IN">India</option>
<option value="UK">United Kingdom</option>
</select><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We check if the selected value is "none". If it is, the user is prompted to select a valid country.
11. Age Range Validation
Assignment: Create a form where the user enters their age, which must be between 18 and 100.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$age = $_POST['age'];
if ($age < 18 || $age > 100) {
echo "Age must be between 18 and 100.";
} else {
echo "Age: " . htmlspecialchars($age);
}
}
?>
<form method="POST">
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We validate that the age entered is within the 18-100 range.
12. Password Strength Validation
Assignment: Create a password field and validate if the password is strong (at least 8 characters, one number, one uppercase letter).
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$password = $_POST['password'];
if (strlen($password) < 8 || !preg_match("/[A-Z]/", $password) || !preg_match("/[0-9]/", $password)) {
echo "Password must be at least 8 characters long, include an uppercase letter and a number.";
} else {
echo "Password is strong.";
}
}
?>
<form method="POST">
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use preg_match() to check for uppercase letters and numbers in the password, while strlen() checks the length.
13. Email Uniqueness Validation
Assignment: Check if an email already exists in a predefined list.
Solution:
<?php
$existingEmails = ["test@example.com", "user@example.com"];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
if (in_array($email, $existingEmails)) {
echo "Email is already taken.";
} else {
echo "Email is available.";
}
}
?>
<form method="POST">
Email: <input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use in_array() to check if the email already exists in the list.
14. File Upload Validation
Assignment: Validate a file upload for an image with a size limit and allowed file types.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$file = $_FILES['file'];
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($file['type'], $allowedTypes)) {
echo "Invalid file type.";
} elseif ($file['size'] > 500000) {
echo "File is too large.";
} else {
echo "File uploaded successfully.";
}
}
?>
<form method="POST" enctype="multipart/form-data">
File: <input type="file" name="file"><br>
<input type="submit" value="Upload">
</form>
Explanation:
- We check the file type using in_array() and the file size with $file['size'].
15. Captcha Validation
Assignment: Implement a simple captcha validation on a form.
Solution:
This example will just demonstrate a simple text captcha.
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$captcha = $_POST['captcha'];
if ($captcha != $_SESSION['captcha']) {
echo "Invalid captcha.";
} else {
echo "Captcha correct.";
}
}
$_SESSION['captcha'] = rand(1000, 9999); // Generate a random captcha
?>
<form method="POST">
Captcha: <?php echo $_SESSION['captcha']; ?><br>
Enter captcha: <input type="text" name="captcha"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We generate a random captcha using rand() and store it in the session. The user needs to enter the captcha value, which is validated against the session value.
16. SQL Injection Prevention
Assignment: Protect a login form from SQL injection.
Solution:
<?php
$conn = new mysqli('localhost', 'root', '', 'test_db');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $conn->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
echo "Login successful!";
} else {
echo "Invalid credentials.";
}
}
?>
<form method="POST">
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
Explanation:
- We use prepared statements ($stmt->prepare()) to prevent SQL injection.
17. Custom Error Messages for Validation
Assignment: Display custom error messages for different validation checks.
Solution:
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
if (empty($name)) {
$errors[] = "Name is required.";
}
$email = $_POST['email'];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
$age = $_POST['age'];
if (!is_numeric($age)) {
$errors[] = "Age must be a number.";
}
if (empty($errors)) {
echo "Form submitted successfully!";
} else {
foreach ($errors as $error) {
echo $error . "<br>";
}
}
}
?>
<form method="POST">
Name: <input type="text" name="name"><br>
Email: <input type="text" name="email"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We store each error message in an array and display them if the form validation fails.
18. Password Complexity Requirements
Assignment: Validate a password that should contain at least one lowercase letter, one uppercase letter, one number, and be at least 8 characters long.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$password = $_POST['password'];
if (strlen($password) < 8 || !preg_match("/[a-z]/", $password) || !preg_match("/[A-Z]/", $password) || !preg_match("/[0-9]/", $password)) {
echo "Password must contain at least one lowercase letter, one uppercase letter, one number, and be at least 8 characters long.";
} else {
echo "Password is strong.";
}
}
?>
<form method="POST">
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use preg_match() to check for the required password complexity.
19. Unique Username Check
Assignment: Ensure that the username entered does not already exist in the database.
Solution:
<?php
$conn = new mysqli('localhost', 'root', '', 'test_db');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
echo "Username is already taken.";
} else {
echo "Username is available.";
}
}
?>
<form method="POST">
Username: <input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We check the database for existing usernames using a prepared statement.
20. XSS Protection
Assignment: Prevent XSS (Cross-Site Scripting) attacks by sanitizing user input before displaying it.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
echo "Hello, " . htmlspecialchars($name);
}
?>
<form method="POST">
Name: <input type="text" name="name"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We use htmlspecialchars() to escape any special characters in the user input, preventing XSS attacks.
21. Age Validation (Minimum Age Limit)
Assignment: Ensure that the age entered is at least 18 years old.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$age = $_POST['age'];
if ($age < 18) {
echo "You must be at least 18 years old.";
} else {
echo "Age is valid.";
}
}
?>
<form method="POST">
Age: <input type="number" name="age"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form checks if the age is greater than or equal to 18.
22. Password Confirmation
Assignment: Check if the password confirmation matches the original password.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$password = $_POST['password'];
$confirmPassword = $_POST['confirmPassword'];
if ($password != $confirmPassword) {
echo "Passwords do not match.";
} else {
echo "Passwords match.";
}
}
?>
<form method="POST">
Password: <input type="password" name="password"><br>
Confirm Password: <input type="password" name="confirmPassword"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form compares the password and confirm password fields to ensure they match.
23. Dropdown Selection Validation
Assignment: Validate if a user has selected an option from a dropdown list.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$selectedOption = $_POST['option'];
if ($selectedOption == 'none') {
echo "Please select an option.";
} else {
echo "Option selected: " . $selectedOption;
}
}
?>
<form method="POST">
Select Option:
<select name="option">
<option value="none">Select...</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form checks if the "none" option is selected, which means the user hasn't made a selection.
24. Date Format Validation
Assignment: Validate if the date entered is in the correct format (YYYY-MM-DD).
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$date = $_POST['date'];
if (!preg_match("/^\d{4}-\d{2}-\d{2}$/", $date)) {
echo "Invalid date format. Please use YYYY-MM-DD.";
} else {
echo "Date is valid.";
}
}
?>
<form method="POST">
Date (YYYY-MM-DD): <input type="text" name="date"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form uses a regular expression to check if the entered date matches the pattern YYYY-MM-DD.
25. Phone Number Validation
Assignment: Validate if the phone number entered is in a valid format (e.g., (XXX) XXX-XXXX).
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$phoneNumber = $_POST['phoneNumber'];
if (!preg_match("/^\(\d{3}\) \d{3}-\d{4}$/", $phoneNumber)) {
echo "Invalid phone number format. Please use (XXX) XXX-XXXX.";
} else {
echo "Phone number is valid.";
}
}
?>
<form method="POST">
Phone Number: <input type="text" name="phoneNumber"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form checks if the phone number matches the format (XXX) XXX-XXXX using a regular expression.
26. Age Range Validation
Assignment: Ensure the age entered is between 18 and 100.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$age = $_POST['age'];
if ($age < 18 || $age > 100) {
echo "Age must be between 18 and 100.";
} else {
echo "Age is valid.";
}
}
?>
<form method="POST">
Age: <input type="number" name="age"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form checks if the entered age is within the range of 18 to 100.
27. URL Validation
Assignment: Validate if a URL is in the correct format.
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$url = $_POST['url'];
if (!filter_var($url, FILTER_VALIDATE_URL)) {
echo "Invalid URL.";
} else {
echo "URL is valid.";
}
}
?>
<form method="POST">
URL: <input type="text" name="url"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form uses PHP's filter_var() function with FILTER_VALIDATE_URL to validate the URL.
28. Credit Card Validation
Assignment: Validate a credit card number using the Luhn algorithm (basic validation).
Solution:
<?php
function isValidCreditCard($number) {
$sum = 0;
$numDigits = strlen($number);
$parity = $numDigits % 2;
for ($i = 0; $i < $numDigits; $i++) {
$digit = (int)$number[$i];
if ($i % 2 == $parity) {
$digit = $digit * 2;
if ($digit > 9) {
$digit -= 9;
}
}
$sum += $digit;
}
return ($sum % 10 == 0);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$cardNumber = $_POST['cardNumber'];
if (!isValidCreditCard($cardNumber)) {
echo "Invalid credit card number.";
} else {
echo "Credit card number is valid.";
}
}
?>
<form method="POST">
Credit Card Number: <input type="text" name="cardNumber"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- We implement the Luhn algorithm to validate the credit card number.
29. Zip Code Validation
Assignment: Validate a zip code entered in the format "XXXXX" or "XXXXX-XXXX".
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$zipCode = $_POST['zipCode'];
if (!preg_match("/^\d{5}(-\d{4})?$/", $zipCode)) {
echo "Invalid zip code. It must be in the format XXXXX or XXXXX-XXXX.";
} else {
echo "Zip code is valid.";
}
}
?>
<form method="POST">
Zip Code: <input type="text" name="zipCode"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form uses a regular expression to check if the zip code is in the valid format.
30. Special Character Validation
Assignment: Check if a username does not contain any special characters (e.g., @, #, $).
Solution:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
if (preg_match("/[^a-zA-Z0-9]/", $username)) {
echo "Username should not contain special characters.";
} else {
echo "Username is valid.";
}
}
?>
<form method="POST">
Username: <input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
Explanation:
- The form checks if the username contains any character that is not a letter or number using a regular expression.