Best Practices for 12 filtration techniques in PHP
1. Input Filtering (Sanitization)
Assignment 1:
Task:
Sanitize a user-entered email address and URL.
Solution:
$email = filter_var($_POST['email'],
FILTER_SANITIZE_EMAIL);
$url = filter_var($_POST['url'],
FILTER_SANITIZE_URL);
echo "Sanitized Email: " . $email;
echo "Sanitized URL:
" . $url;
Explanation:
The FILTER_SANITIZE_EMAIL filter removes any unwanted characters from the email
input, while the FILTER_SANITIZE_URL filter cleans the URL input to prevent
invalid URLs or malicious data.
Assignment 2:
Task:
Sanitize a user-provided username by removing any unwanted characters.
Solution:
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
echo "Sanitized
Username: " . $username;
Explanation:
The FILTER_SANITIZE_STRING filter removes tags and special characters from the
input, ensuring that only a clean string is accepted.
Assignment 3:
Task:
Sanitize user input for an address, removing unwanted special characters.
Solution:
$address = filter_var($_POST['address'], FILTER_SANITIZE_SPECIAL_CHARS);
echo "Sanitized
Address: " . $address;
Explanation:
The FILTER_SANITIZE_SPECIAL_CHARS function converts special characters like <
or > into their HTML entity equivalents (< and >), preventing
them from being interpreted as HTML.
Assignment 4:
Task: Validate a URL to ensure it is well-formed.
Solution:
$url = $_POST['url'];
if (filter_var($url, FILTER_VALIDATE_URL)) {
echo "Valid URL.";
} else {
echo "Invalid URL.";
}
Explanation: This checks if the provided URL is a valid URL format.
Assignment 5:
Task: Validate a date input (in YYYY-MM-DD format).
Solution:
$date = $_POST['date'];
if (DateTime::createFromFormat('Y-m-d', $date) !== false) {
echo "Valid date.";
} else {
echo "Invalid date.";
}
Explanation: This ensures that the date is in the correct format YYYY-MM-DD and checks its validity.
Assignment 1:
Task: Sanitize an email address to remove unwanted characters.
Solution:
$email = $_POST['email'];
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
echo "Sanitized email: " . $sanitized_email;
Explanation: This removes any unwanted characters from the email address to make it safe for use.
Assignment 2:
Task: Sanitize a URL input.
Solution:
$url = $_POST['url'];
$sanitized_url = filter_var($url, FILTER_SANITIZE_URL);
echo "Sanitized URL: " . $sanitized_url;
Explanation: This sanitizes the URL input, removing invalid characters that could cause problems.
2. Output Filtering
Assignment 1:
Task:
Use htmlspecialchars to safely output user input on a webpage.
Solution:
$user_input = "<script>alert('Hacked!');</script>";
echo htmlspecialchars($user_input,
ENT_QUOTES, 'UTF-8');
Explanation:
The htmlspecialchars() function converts special characters into HTML entities.
It ensures that a script tag will not be executed, preventing XSS attacks.
Assignment 2:
Task:
Encode HTML entities before displaying user input.
Solution:
$user_input = "<b>Welcome!</b>";
echo htmlentities($user_input,
ENT_QUOTES, 'UTF-8');
Explanation:
The htmlentities() function converts any special characters in the input into
HTML entities. It provides an extra layer of protection against XSS attacks.
Assignment 3:
Task:
Safely display a username submitted by the user without executing any HTML or
JavaScript.
Solution:
$username = $_POST['username'];
echo htmlspecialchars($username,
ENT_QUOTES, 'UTF-8');
Explanation:
This example ensures that any HTML tags or script attempts in the username
input are converted to HTML-safe entities.
3. SQL Injection
Prevention
Assignment 1:
Task:
Prevent SQL injection by using parameterized queries.
Solution:
$conn = new mysqli("localhost", "user", "password", "db");
$stmt = $conn->prepare("SELECT
* FROM users WHERE username = ?");
$stmt->bind_param("s",
$_POST['username']);
$stmt->execute();
Explanation:
Using prepared statements and parameterized queries (bind_param) prevents SQL
injection, as the user input is treated as data, not part of the SQL query.
Assignment 2:
Task:
Sanitize input to prevent SQL injection by escaping special characters.
Solution:
$username = mysqli_real_escape_string($conn, $_POST['username']);
$query = "SELECT *
FROM users WHERE username = '$username'";
mysqli_query($conn, $query);
Explanation:
mysqli_real_escape_string() escapes special characters in user input, ensuring
that characters like ' and " don't break the query syntax.
Assignment 3:
Task:
Use PDO to prevent SQL injection while selecting user data.
Solution:
$conn = new PDO("mysql:host=localhost;dbname=db", "user", "password");
$stmt = $conn->prepare("SELECT
* FROM users WHERE username = :username");
$stmt->execute(['username'
=> $_POST['username']]);
Explanation:
Using PDO with prepared statements and bound parameters (:username) prevents
SQL injection by ensuring the user input is safely handled.
4. File Upload Filtering
Assignment 1:
Task:
Filter file upload to accept only JPEG and PNG image types.
Solution:
if ($_FILES['image']['type'] != 'image/jpeg' && $_FILES['image']['type'] != 'image/png') {
echo "Only JPG and PNG files are
allowed.";
} else {
echo "File uploaded
successfully.";
}
Explanation:
This checks the file type against allowed image types (JPEG and PNG) to ensure
that only these formats are accepted for upload.
Assignment 2:
Task:
Limit file upload size to 5MB.
Solution:
if ($_FILES['file']['size'] > 5000000) {
echo "File is too large!";
} else {
echo "File uploaded
successfully.";
}
Explanation:
The file size is checked to ensure that the uploaded file does not exceed the
5MB limit. If it does, the upload is prevented.
Assignment 3:
Task:
Sanitize a file name before saving it to the server.
Solution:
$file_name = basename($_FILES['file']['name']);
$file_name = preg_replace("/[^a-zA-Z0-9.]/",
"", $file_name);
move_uploaded_file($_FILES['file']['tmp_name'],
"uploads/" . $file_name);
Explanation:
This sanitizes the file name by removing any characters that could be harmful
or unexpected, allowing only alphanumeric characters and periods (.).
5. URL Filtering
Assignment 1:
Task:
Validate that a user-provided URL is a valid URL.
Solution:
$url = $_POST['url'];
if (filter_var($url,
FILTER_VALIDATE_URL)) {
echo "Valid URL.";
} else {
echo "Invalid URL.";
}
Explanation:
The FILTER_VALIDATE_URL filter validates that the input is a valid URL,
preventing invalid or harmful URLs.
Assignment 2:
Task:
Sanitize a user-provided URL before storing it.
Solution:
$url = filter_var($_POST['url'], FILTER_SANITIZE_URL);
echo "Sanitized URL:
" . $url;
Explanation:
The FILTER_SANITIZE_URL function sanitizes the URL by removing any illegal
characters.
Assignment 3:
Task:
Ensure that the URL starts with "https://".
Solution:
$url = $_POST['url'];
if (substr($url, 0, 8) !=
"https://") {
echo "URL must start with
https://";
} else {
echo "Valid URL.";
}
Explanation:
This checks that the user-provided URL starts with https://, enforcing secure
URLs.
6. CSRF (Cross-Site
Request Forgery) Token Filtering
Assignment 1:
Task:
Generate a CSRF token and validate it upon form submission.
Solution:
// Generate CSRF token
$_SESSION['csrf_token'] =
bin2hex(random_bytes(32));
// Include CSRF token in the form
echo '<input
type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token']
. '">';
// Validate CSRF token upon form submission
if ($_POST['csrf_token']
!== $_SESSION['csrf_token']) {
die("Invalid CSRF token");
} else {
echo "Form submitted
successfully!";
}
Explanation:
This ensures that each form submission includes a unique token, which is
checked against the session's token to prevent CSRF attacks.
Assignment 2:
Task:
Use CSRF token protection in an update form.
Solution:
// Generate token
$_SESSION['csrf_token'] =
bin2hex(random_bytes(32));
// Validate token when form is submitted
if ($_POST['csrf_token']
!== $_SESSION['csrf_token']) {
echo "Invalid CSRF token.";
exit();
}
Explanation:
This protects the form against CSRF by ensuring that only valid requests can
submit the form data.
Assignment 3:
Task:
Display CSRF token in an HTML form.
Solution:
// Store CSRF token in session
$_SESSION['csrf_token'] =
bin2hex(random_bytes(32));
// Display hidden field with CSRF token in the form
echo '<form
method="POST">';
echo '<input
type="hidden" name="csrf_token" value="' . $_SESSION['csrf_token']
. '">';
echo '<input
type="submit" value="Submit">';
echo '</form>';
Explanation:
The CSRF token is added as a hidden field in the form to be checked upon
submission.
Assignment 1:
Task: Use htmlspecialchars to escape potentially harmful input.
Solution:
php
Copy code
$user_input = $_POST['user_input'];
$safe_input = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo "Safe input: " . $safe_input;
Explanation: This ensures that user input is safely encoded to prevent any malicious HTML or JavaScript from being executed.
Assignment 2:
Task: Sanitize a comment to prevent XSS.
Solution:
php
Copy code
$comment = $_POST['comment'];
$sanitized_comment = filter_var($comment, FILTER_SANITIZE_STRING);
echo "Sanitized comment: " . $sanitized_comment;
Explanation: This sanitizes the comment by removing any potentially dangerous HTML or JavaScript.
7. Regex Filtering
(Regular Expressions)
Assignment 1:
Task:
Validate an email address using regex.
Solution:
$email = $_POST['email'];
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/",
$email)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
Explanation:
This regex checks if the input matches a standard email format, allowing
alphanumeric characters and certain symbols.
Assignment 2:
Task:
Validate a phone number using regex (only digits).
Solution:
$phone = $_POST['phone'];
if (preg_match("/^\d{10}$/",
$phone)) {
echo "Valid phone number.";
} else {
echo "Invalid phone number.";
}
Explanation:
This regex checks if the phone number contains exactly 10 digits, allowing only
numeric input.
Assignment 3:
Task:
Use regex to validate a username (only alphanumeric characters allowed).
Solution:
$username = $_POST['username'];
if (preg_match("/^[a-zA-Z0-9]+$/",
$username)) {
echo "Valid username.";
} else {
echo "Invalid username.";
}
Explanation:
This regex ensures that the username consists only of alphanumeric characters,
no special symbols or spaces.
Assignment 1:
Task: Validate a password to ensure it contains at least one uppercase letter, one lowercase letter, one number, and is at least 8 characters long.
Solution:
php
Copy code
$password = $_POST['password'];
if (preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/", $password)) {
echo "Valid password.";
} else {
echo "Invalid password.";
}
Explanation: This regular expression checks that the password contains uppercase, lowercase, and numeric characters, and has a minimum length of 8 characters.
Assignment 2:
Task: Validate a US phone number (format: (XXX) XXX-XXXX).
Solution:
php
Copy code
$phone = $_POST['phone'];
if (preg_match("/^\(\d{3}\) \d{3}-\d{4}$/", $phone)) {
echo "Valid phone number.";
} else {
echo "Invalid phone number.";
}
Explanation: This regular expression validates a phone number in the format (XXX) XXX-XXXX.
8. Header Filtering
Assignment 1:
Task:
Prevent XSS by setting appropriate HTTP headers for the content.
Solution:
header("Content-Security-Policy:
default-src 'self'");
Explanation:
The Content-Security-Policy header restricts which resources the browser is
allowed to load, helping mitigate XSS vulnerabilities.
Assignment 2:
Task:
Use headers to prevent clickjacking.
Solution:
header("X-Frame-Options:
DENY");
Explanation:
The X-Frame-Options header prevents the page from being embedded in iframes,
protecting against clickjacking attacks.
Assignment 3:
Task:
Prevent content type sniffing by setting the appropriate header.
Solution:
header("X-Content-Type-Options:
nosniff");
Explanation:
This header prevents browsers from interpreting files as something other than
their declared content type, preventing MIME sniffing attacks.
9. Input Length Validation
Assignment 1:
Task:
Ensure that the user’s password is at least 8 characters long.
Solution:
$password = $_POST['password'];
if (strlen($password)
>= 8) {
echo "Password length is valid.";
} else {
echo "Password must be at least 8
characters.";
}
Explanation:
This checks that the password length meets a minimum requirement of 8
characters.
Assignment 2:
Task:
Validate that a username is between 5 and 15 characters long.
Solution:
$username = $_POST['username'];
if (strlen($username)
>= 5 && strlen($username) <= 15) {
echo "Valid username length.";
} else {
echo "Username must be between 5 and
15 characters.";
}
Explanation:
This ensures that the username length falls within the specified range.
Assignment 3:
Task:
Validate the length of an email address to ensure it is not too long.
Solution:
$email = $_POST['email'];
if (strlen($email) <= 255)
{
echo "Valid email length.";
} else {
echo "Email is too long.";
}
Explanation:
This checks the email length to make sure it is within the standard email
length limit of 255 characters.
Assignment 1:
Task: Ensure a password is at least 12 characters long.
Solution:
php
Copy code
$password = $_POST['password'];
if (strlen($password) >= 12) {
echo "Valid password length.";
} else {
echo "Password must be at least 12 characters.";
}
Explanation: This checks if the password meets the required minimum length.
Assignment 2:
Task: Validate that a comment field does not exceed 500 characters.
Solution:
php
Copy code
$comment = $_POST['comment'];
if (strlen($comment) <= 500) {
echo "Valid comment length.";
} else {
echo "Comment too long, max 500 characters.";
}
Explanation: This ensures that the comment does not exceed the maximum allowed length of 500 characters.
10. Character Encoding
Filtering
Assignment 1:
Task:
Ensure that a user input is encoded in UTF-8.
Solution:
$user_input = $_POST['input'];
$encoded_input = mb_convert_encoding($user_input,
"UTF-8");
echo "Encoded input:
" . $encoded_input;
Explanation:
This ensures that user input is converted to UTF-8 encoding, which supports a
wide range of characters and languages.
Assignment 2:
Task:
Convert a string from ISO-8859-1 to UTF-8 encoding.
Solution:
$string = $_POST['string'];
$converted_string = mb_convert_encoding($string,
"UTF-8", "ISO-8859-1");
echo "Converted
string: " . $converted_string;
Explanation:
This converts the string from the ISO-8859-1 encoding to UTF-8, which is more
widely supported.
Assignment 3:
Task:
Prevent multibyte characters from breaking the application.
Solution:
$input = $_POST['input'];
if (mb_check_encoding($input,
"UTF-8")) {
echo "Valid UTF-8 encoding.";
} else {
echo "Invalid UTF-8 encoding.";
}
Explanation:
This checks if the input is valid UTF-8 encoded data, ensuring the proper
handling of multibyte characters.
11. Content-Type
Filtering
Assignment 1:
Task:
Check the content type of a file before processing it.
Solution:
$file = $_FILES['file'];
if ($file['type'] == 'image/jpeg')
{
echo "Valid file type.";
} else {
echo "Invalid file type.";
}
Explanation:
This ensures that the uploaded file is of the JPEG type before allowing it to
be processed.
Assignment 2:
Task:
Reject any uploaded files that are not of the application/pdf content type.
Solution:
$file = $_FILES['file'];
if ($file['type'] == 'application/pdf')
{
echo "Valid PDF file.";
} else {
echo "Only PDF files are
allowed.";
}
Explanation:
This restricts uploads to only PDF files by checking the file type.
Assignment 3:
Task:
Ensure that only text files are uploaded.
Solution:
$file = $_FILES['file'];
if ($file['type'] == 'text/plain')
{
echo "Valid text file.";
} else {
echo "Only text files are
allowed.";
}
Explanation:
This ensures that only text files (MIME type text/plain) can be uploaded.
Assignment 1:
Task: Restrict uploads to only image files (PNG and JPEG).
Solution:
php
Copy code
$file = $_FILES['file'];
if ($file['type'] == 'image/png' || $file['type'] == 'image/jpeg') {
echo "Valid image file.";
} else {
echo "Invalid file type.";
}
Explanation: This filters the file upload, allowing only PNG and JPEG image files.
Assignment 2:
Task: Ensure only Excel files (.xls, .xlsx) are uploaded.
Solution:
php
Copy code
$file = $_FILES['file'];
$allowed_types = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if (in_array($file['type'], $allowed_types)) {
echo "Valid Excel file.";
} else {
echo "Invalid file type.";
}
Explanation: This checks if the uploaded file type is in the allowed list of Excel file types.
Assignment 1:
Task: Validate that a variable is an integer.
Solution:
php
Copy code
$number = $_POST['number'];
if (filter_var($number, FILTER_VALIDATE_INT)) {
echo "Valid integer.";
} else {
echo "Invalid integer.";
}
Explanation: This ensures that the provided input is a valid integer.
Assignment 2:
Task: Validate that a variable is a float.
Solution:
php
Copy code
$float_number = $_POST['float_number'];
if (filter_var($float_number, FILTER_VALIDATE_FLOAT)) {
echo "Valid float.";
} else {
echo "Invalid float.";
}
Explanation: This checks if the input is a valid float number.
12. Whitelist Filtering
Assignment 1:
Task:
Check if a username is in an approved list of usernames.
Solution:
$approved_usernames = ['admin',
'user', 'guest'];
$username = $_POST['username'];
if (in_array($username, $approved_usernames))
{
echo "Welcome, " . $username;
} else {
echo "Invalid username.";
}
Explanation:
This checks whether the provided username is part of a predefined set of
allowed usernames.
Assignment 2:
Task:
Ensure that only allowed file types are uploaded (PDF, Word, or Excel).
Solution:
$allowed_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
$file = $_FILES['file'];
if (in_array($file['type'],
$allowed_types)) {
echo "File type is allowed.";
} else {
echo "Invalid file type.";
}
Explanation:
This filters the file upload based on a whitelist of allowed MIME types.
Assignment 3:
Task:
Check if a user’s role is one of the predefined valid roles (admin, user, moderator).
Solution:
$valid_roles = ['admin', 'user', 'moderator'];
$role = $_POST['role'];
if (in_array($role, $valid_roles))
{
echo "Valid role.";
} else {
echo "Invalid role.";
}
Explanation:
This validates that the user's role matches one of the predefined, acceptable
roles.
Assignment 4:
Task: Check if a given email domain is in the approved list of domains.
Solution:
$approved_domains = ['example.com', 'mydomain.com'];
$email = $_POST['email'];
$domain = substr(strrchr($email, "@"), 1);
if (in_array($domain, $approved_domains)) {
echo "Approved email domain.";
} else {
echo "Unapproved email domain.";
}
Explanation: This extracts the domain from the email and checks if it matches one of the approved domains.
Assignment 5:
Task: Ensure that only certain usernames are allowed from a whitelist.
Solution:
$allowed_usernames = ['admin', 'manager', 'user'];
$username = $_POST['username'];
if (in_array($username, $allowed_usernames)) {
echo "Welcome, " . $username;
} else {
echo "Access denied.";
}
Explanation: This validates the username by ensuring it is in the approved list of usernames.
13. Header Filtering
Assignment 1:
Task: Set the header to prevent content sniffing.
Solution:
header("X-Content-Type-Options: nosniff");
Explanation: This header prevents browsers from interpreting files as a different MIME type than declared, enhancing security.
Assignment 2:
Task: Set the Strict-Transport-Security header to enforce HTTPS.
Solution:
header("Strict-Transport-Security: max-age=31536000; includeSubDomains");
Explanation: This header enforces the use of HTTPS for all future requests for a year (31536000 seconds), protecting against man-in-the-middle attacks.
14. Content Security Policy (CSP)
Assignment 1:
Task: Implement a CSP header to allow only scripts from the same origin.
Solution:
header("Content-Security-Policy: script-src 'self';");
Explanation: This restricts the execution of JavaScript to the same origin (the website itself).
Assignment 2:
Task: Enforce a CSP policy that allows images only from the same domain.
Solution:
header("Content-Security-Policy: img-src 'self';");
Explanation: This restricts image sources to be loaded only from the same domain.
15. Session Management
Assignment 1:
Task: Regenerate the session ID after a successful login.
Solution:
session_start();
session_regenerate_id(true);
echo "Session ID regenerated.";
Explanation: This prevents session fixation attacks by regenerating the session ID after login.
Assignment 2:
Task: Set a session timeout to expire after 30 minutes of inactivity.
Solution:
session_start();
$timeout = 1800; // 30 minutes
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout)) {
session_unset();
session_destroy();
echo "Session expired.";
} else {
$_SESSION['last_activity'] = time();
}
Explanation: This tracks the last activity time and expires the session after 30 minutes of inactivity.
16. Database Security
Assignment 1:
Task: Use prepared statements to prevent SQL injection in a login form.
Solution:
$conn = new mysqli("localhost", "username", "password", "database");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
Explanation: This uses prepared statements to ensure that the input is safely handled and avoids SQL injection.
Assignment 2:
Task: Prevent SQL injection by escaping user input.
Solution:
$conn = new mysqli("localhost", "username", "password", "database");
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
Explanation: This escapes any special characters in the input to prevent SQL injection.