What is it?
Validation checks whether data meets your rules (is this a valid email?). Sanitization cleans data to remove dangerous characters. You need both, but in the right order — validate first, sanitize output.
Why does it matter?
Every security breach involving user-submitted data traces back to trusting input without validation. SQL injection, XSS attacks, and data corruption all start with unvalidated input.
Learn validation vs sanitization, filter_var, custom rules, and a reusable Validator class.
Real-World Use Cases
- 📝 Registration form - Validate username length, email format, and password strength before inserting to the database.
- 💳 Payment form - Validate that amount is a positive float, card number is 16 digits, and CVV is 3-4 digits before passing to the payment gateway.
- 🔍 Search input - Validate search query is a non-empty string under 200 characters, sanitize HTML entities before displaying results.
- 📁 File uploads - Validate MIME type is an allowed image type, check file size is under 2MB, and sanitize the filename before saving.
filter_var — Built-in Validation
PHP provides filter_var() for common validations.
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
//other filters
filter_var($url, FILTER_VALIDATE_URL);
filter_var($ip, FILTER_VALIDATE_IP);
filter_var($number, FILTER_VALIDATE_INT);
Advantages
- Fast
- Built into PHP
- Good for standard validation
Custom Validation Function
When business rules are unique.
function validateUsername($username)
{
return preg_match('/^[a-zA-Z0-9_]{5,15}$/', $username);
}
if (validateUsername("shivom_123")) {
echo "Valid Username";
} else {
echo "Invalid Username";
}
Rules
- Only letters, numbers, underscore
- Length between 5 and 15
Advantages
- Flexible
- Easy to modify
Reusable Validator Class
Best for large projects.
class Validator
{
public static function email($email)
{
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
public static function mobile($mobile)
{
return preg_match('/^[0-9]{10}$/', $mobile);
}
public static function required($value)
{
return !empty(trim($value));
}
}
//usage
if (Validator::email("test@example.com")) {
echo "Email Valid";
}
if (Validator::mobile("9876543210")) {
echo "Mobile Valid";
}
if (Validator::required("Shivom")) {
echo "Value Present";
}
Advantages
- Reusable
- Centralized validation
- Easy maintenance
- Suitable for MVC frameworks like CodeIgniter/Laravel
Q: Is sanitization alone enough to prevent SQL injection?
No. Sanitization modifies input but is not a defence against SQL injection. The correct defence is prepared statements. Sanitization is for preventing XSS when displaying output in HTML.
Comments (0)
No comments yet. Be the first!
Leave a Comment