PHP Data Sanitization & Validation

PHP Data Sanitization & Validation – Secure User Input 🛡️

Imagine you’re running a website where users enter their name and email. What if someone enters <script>alert('Hacked!')</script> instead? 😱

This is why data sanitization and validation are crucial. Let’s make sure your PHP forms accept only clean and valid data! ✅


🚀 What is Data Sanitization?

Sanitization is the process of cleaning user input by removing or encoding harmful characters. This prevents SQL injection, XSS attacks, and broken application behavior.

✅ Example: Using filter_var() for Sanitization

Let’s sanitize a user’s email input.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    echo "Sanitized Email: " . $email;
}
?>

Try It Now

🔒 Why is this secure? It removes unwanted characters like spaces and dangerous symbols from email input.


🚦 What is Data Validation?

Validation checks if the input meets specific criteria, like:

  • 📧 Is it a valid email?
  • 📞 Is it a proper phone number?
  • 🔢 Is it a number?

✅ Example: Validating an Email

Here’s how to verify if an email is valid:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];

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

Try It Now

🎯 Key Difference: FILTER_SANITIZE_EMAIL cleans the email, while FILTER_VALIDATE_EMAIL checks if it’s actually valid.


🔢 Validating Numbers

Ensure a user enters a valid integer:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $age = $_POST['age'];

    if (filter_var($age, FILTER_VALIDATE_INT)) {
        echo "Valid Age: " . $age;
    } else {
        echo "Invalid Age!";
    }
}
?>

Try It Now

✅ Best Practice: Always validate numeric input before using it in calculations.


📞 Validating Phone Numbers

Let’s allow only numbers and dashes in a phone number:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $phone = filter_var($_POST['phone'], FILTER_SANITIZE_NUMBER_INT);
    echo "Sanitized Phone: " . $phone;
}
?>

Try It Now

🔒 Why is this useful? It removes letters and unwanted symbols, keeping only numbers.


💬 Removing HTML Tags

To strip HTML tags from user input:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $comment = strip_tags($_POST['comment']);
    echo "Clean Comment: " . $comment;
}
?>

Try It Now

🛡️ Why use this? Prevents users from injecting malicious scripts into comments.


🎯 Best Practices for Secure Data Handling

  • ✅ Always sanitize input before storing it.
  • Validate data before using it in logic.
  • ✅ Use htmlspecialchars() when displaying user input.
  • ✅ Escape special characters when working with databases.

🚀 Next Steps

Try modifying the examples and experimenting with different inputs. Secure your PHP applications today! 💪