PHP

Sanitize User Input to Prevent XSS and SQL Injection

Learn to securely sanitize user input in PHP using `htmlspecialchars` and prepared statements, crucial for preventing Cross-Site Scripting (XSS) and SQL Injection vulnerabilities.

<?php
// Function to sanitize string input for display/HTML context
function sanitizeForHtml($input) {
    return htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
}

// Example of sanitizing user input before displaying
$userInput = "<script>alert('XSS!');</script>";
$safeOutput = sanitizeForHtml($userInput);
// echo $safeOutput; // Outputs: &lt;script&gt;alert(&#039;XSS!&#039;);&lt;/script&gt;

// --- For database interactions (SQL Injection prevention) ---
// ALWAYS use prepared statements with parameterized queries.
// Example using PDO:
try {
    $pdo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $userId = 123;
    $comment = "User comment with 'quotes' and potentially malicious input; DROP TABLE users;";

    // Prepare the statement
    $stmt = $pdo->prepare("INSERT INTO comments (user_id, comment_text) VALUES (:user_id, :comment_text)");

    // Bind parameters
    $stmt->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmt->bindParam(':comment_text', $comment, PDO::PARAM_STR);

    // Execute the statement
    $stmt->execute();

    // echo "Comment added successfully without SQL Injection risk.";

} catch (PDOException $e) {
    // Log the error, do not display to user in production
    error_log("Database error: " . $e->getMessage());
    // echo "An error occurred.";
}
?>
How it works: This snippet demonstrates two critical aspects of input sanitization. `sanitizeForHtml` uses `htmlspecialchars` to convert special characters into HTML entities, preventing XSS attacks when displaying user-generated content. For database interactions, it's crucial to use prepared statements with parameterized queries (shown with PDO). This separates the SQL logic from the data, effectively neutralizing SQL injection attempts by ensuring user input is treated as data, not executable code.

Need help integrating this into your project?

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

Hire DigitalCodeLabs