← Back to all snippets
PHP

Secure Server-Side Input Sanitization and Validation

Prevent various injection attacks (SQL, XSS, Path Traversal) by performing rigorous server-side sanitization and validation on all user inputs.

<?php
function sanitizeAndValidateInput($data) {
    $sanitizedData = [];

    // Example for a string input (e.g., username, title)
    if (isset($data['username'])) {
        $username = trim($data['username']);
        $username = filter_var($username, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
        $username = htmlspecialchars($username, ENT_QUOTES, 'UTF-8'); // For display later, redundant if always prepared statements

        // Basic validation
        if (empty($username) || !preg_match("/^[a-zA-Z0-9_]{3,20}$/", $username)) {
            // Handle error: Invalid username
            return ['error' => 'Invalid username format.'];
        }
        $sanitizedData['username'] = $username;
    }

    // Example for an integer input (e.g., ID)
    if (isset($data['id'])) {
        $id = filter_var($data['id'], FILTER_VALIDATE_INT);
        if ($id === false) {
            // Handle error: Invalid ID
            return ['error' => 'Invalid ID.'];
        }
        $sanitizedData['id'] = $id;
    }

    // Example for a URL input
    if (isset($data['website'])) {
        $website = filter_var($data['website'], FILTER_SANITIZE_URL);
        if (!filter_var($website, FILTER_VALIDATE_URL)) {
            // Handle error: Invalid URL
            return ['error' => 'Invalid website URL.'];
        }
        $sanitizedData['website'] = $website;
    }

    // More input types...
    return $sanitizedData;
}

// Example Usage:
// $userInput = ['username' => 'test_user123', 'id' => '123', 'website' => 'http://example.com'];
// $processedInput = sanitizeAndValidateInput($userInput);

// if (isset($processedInput['error'])) {
//     echo $processedInput['error'];
// } else {
//     // Use $processedInput for database operations or further processing
//     // e.g., $stmt->execute([$processedInput['username'], $processedInput['id']]);
//     print_r($processedInput);
// }
?>
How it works: This PHP snippet demonstrates robust server-side input sanitization and validation. It uses `filter_var` to clean and validate different types of user input, such as strings, integers, and URLs. `FILTER_SANITIZE_STRING` removes tags and potentially harmful characters, while `FILTER_VALIDATE_INT` and `FILTER_VALIDATE_URL` ensure data conforms to expected formats. Additionally, `htmlspecialchars` is used for strings intended for HTML output (though prepared statements are preferred for database interactions). This multi-layered approach is crucial for preventing XSS, SQL injection, and other vulnerabilities.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs