Lesson 35 of 50 – PHP Input Sanitization
70%

PHP Input Sanitization

Input sanitization helps us handle user-provided data safely. In PHP, we can trim unnecessary whitespace, validate input, escape output, and use prepared statements when working with databases.

1. What Is Input Sanitization?

Input sanitization means cleaning or normalizing input when appropriate. Validation checks whether input follows the rules we expect.

  • Sanitization: Cleans or transforms data.
  • Validation: Checks whether data is acceptable.
  • Output escaping: Makes data safe for a particular output context, such as HTML.
<?php
$name = trim("  Rahul  ");

if ($name === "") {
    echo "Name is required.";
} else {
    echo "Name is valid.";
}
?>

Output: Name is valid.

Remember: cleaning input does not replace validation or context-specific output escaping.

2. Using trim() to Remove Extra Whitespace

The trim() function removes whitespace from the beginning and end of a string.

<?php
$name = "   Rahul Kumar   ";

$cleanName = trim($name);

echo $cleanName;
?>

Output: Rahul Kumar

Other useful functions
  • ltrim() removes whitespace from the beginning.
  • rtrim() removes whitespace from the end.
<?php
$text = "   Hello PHP   ";

echo "[" . ltrim($text) . "]<br>";
echo "[" . rtrim($text) . "]<br>";
echo "[" . trim($text) . "]";
?>

Output:

[Hello PHP   ]
[   Hello PHP]
[Hello PHP]
3. Using htmlspecialchars() for Safe HTML Output

The htmlspecialchars() function converts special HTML characters into HTML entities. It is commonly used when displaying user input inside HTML.

<?php
$comment = '<script>alert("Hello");</script>';

echo htmlspecialchars(
    $comment,
    ENT_QUOTES | ENT_SUBSTITUTE,
    'UTF-8'
);
?>

The browser displays the script text instead of interpreting it as an HTML script element.

Important: This is output escaping, not general-purpose input sanitization. Escape data when outputting it in the appropriate context.

<?php
$name = '<Rahul>';

echo "<p>Student: "
    . htmlspecialchars($name, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
    . "</p>";
?>

Displayed result: Student: <Rahul>

4. Using filter_var() for Email Data

The filter_var() function can sanitize or validate data depending on the filter used.

Sanitize an email string
<?php
$email = "  rahul@example.com  ";

$cleanEmail = trim($email);
$cleanEmail = filter_var(
    $cleanEmail,
    FILTER_SANITIZE_EMAIL
);

echo $cleanEmail;
?>

Output: rahul@example.com

Validate an email address
<?php
$email = "rahul@example.com";

if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
    echo "Valid email format.";
} else {
    echo "Invalid email format.";
}
?>

Output: Valid email format.

Email format validation does not prove that the mailbox exists or belongs to the user.

5. Using filter_input()

The filter_input() function reads a value from an external input source, such as GET or POST, and applies a filter.

Example: Read and validate an age from GET
<?php
$age = filter_input(
    INPUT_GET,
    'age',
    FILTER_VALIDATE_INT
);

if ($age !== null && $age !== false && $age >= 18) {
    echo "Eligible.";
} else {
    echo "Please provide a valid age of 18 or above.";
}
?>

Test this example with a URL such as:

http://localhost/project.php?age=20

Output: Eligible.

The function reads the original external request input. In command-line execution or some testing environments, it may return null or false instead of a usable value.

6. Sanitizing and Validating URLs

PHP provides filters for cleaning URL strings and checking whether a string has a valid URL format.

<?php
$url = "https://example.com/page";

$cleanUrl = filter_var(
    $url,
    FILTER_SANITIZE_URL
);

if (filter_var($cleanUrl, FILTER_VALIDATE_URL) !== false) {
    echo "Valid URL: " . htmlspecialchars(
        $cleanUrl,
        ENT_QUOTES | ENT_SUBSTITUTE,
        'UTF-8'
    );
} else {
    echo "Invalid URL.";
}
?>

Output: Valid URL: https://example.com/page

Sanitizing a URL does not establish that it is trustworthy. If your application allows links, also consider an allowlist of permitted schemes such as https.

Avoid the old FILTER_SANITIZE_STRING filter; it was deprecated in PHP 8.1 and removed in PHP 8.3.

7. Sanitizing and Validating Numeric Data

When accepting marks, age, quantity, or fees, validate the expected data type and any required range.

<?php
$input = "85";

$marks = filter_var($input, FILTER_VALIDATE_INT);

if ($marks !== false && $marks >= 0 && $marks <= 100) {
    echo "Valid marks: " . $marks;
} else {
    echo "Enter a whole number between 0 and 100.";
}
?>

Output: Valid marks: 85

Example with invalid data
<?php
$input = "85abc";

$marks = filter_var($input, FILTER_VALIDATE_INT);

if ($marks === false) {
    echo "Invalid integer.";
}
?>

Output: Invalid integer.

Do not rely on sanitization alone for numeric data. Always validate business rules, such as marks being between 0 and 100.

8. Safe Database Queries with PDO

Input sanitization is not a replacement for protection against SQL injection. Use PDO prepared statements when inserting or querying user-provided values.

<?php
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');

if ($name === '' ||
    filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    exit("Please enter a valid name and email.");
}

$pdo = new PDO(
    "mysql:host=localhost;dbname=school;charset=utf8mb4",
    "root",
    "",
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
);

$sql = "INSERT INTO students (name, email)
        VALUES (:name, :email)";

$stmt = $pdo->prepare($sql);

$stmt->execute([
    'name' => $name,
    'email' => $email
]);

echo "Student saved successfully.";
?>

This example assumes the school database and a students table with name and email columns already exist.

  • Validate input before accepting it.
  • Use prepared statements for database values.
  • Escape output separately when displaying data in HTML.
9. Practical Example: Student Registration Form

This example trims the name, validates the email, and escapes both values before displaying them.

<?php
$name = '';
$email = '';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');

    if ($name === '') {
        $message = "Please enter your name.";
    } elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        $message = "Please enter a valid email address.";
    } else {
        $message = "Registration details are valid.";
    }
}
?>

<form method="post">
    <label for="name">Student Name:</label>
    <input type="text" id="name" name="name" required>

    <br><br>

    <label for="email">Email Address:</label>
    <input type="text" id="email" name="email" required>

    <br><br>

    <button type="submit">Register</button>
</form>

<?php if ($message !== ''): ?>
    <p>
        <?= htmlspecialchars(
            $message,
            ENT_QUOTES | ENT_SUBSTITUTE,
            'UTF-8'
        ) ?>
    </p>

    <p>Name:
        <?= htmlspecialchars(
            $name,
            ENT_QUOTES | ENT_SUBSTITUTE,
            'UTF-8'
        ) ?>
    </p>

    <p>Email:
        <?= htmlspecialchars(
            $email,
            ENT_QUOTES | ENT_SUBSTITUTE,
            'UTF-8'
        ) ?>
    </p>
<?php endif; ?>

This example validates the submitted values but does not save them to a database. Add prepared statements if you want to store the registration details.


🧠 Quick Quiz

1. Which function removes whitespace from both ends of a string?




2. Which function is commonly used to escape special characters when displaying text inside HTML?




3. What is the recommended way to insert user input into a PDO database query?