25
1
0
How To Sanitize and Validate User Input in PHP

How To Sanitize and Validate User Input in PHP

Published on July 3, 2025 by OBSCountdown Editorial

Sanitize and Validate User Input in PHP

Improve security by learning to sanitize and validate all user input in PHP using filters and best practices.

๐Ÿ” Why Sanitize and Validate Input?

User input is one of the most common attack vectors for web applications. To protect your PHP apps from XSS, SQL injection, and other vulnerabilities, it's essential to sanitize and validate all incoming data.

๐Ÿงผ Sanitizing Input

Sanitizing removes unwanted characters or HTML from the input to ensure it's safe to process.

Examples:

<?php
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$url = filter_var($_POST['website'], FILTER_SANITIZE_URL);
?>

Use these filters to prevent users from injecting scripts, broken markup, or malformed data.

โœ”๏ธ Validating Input

Validation checks whether the input matches an expected format or type.

Examples:

<?php
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "Valid email";
} else {
  echo "Invalid email";
}

if (filter_var($url, FILTER_VALIDATE_URL)) {
  echo "Valid URL";
}
?>

๐Ÿ“ Custom Validation with Regex

<?php
$username = $_POST['username'];
if (preg_match("/^[a-zA-Z0-9_]{3,20}$/", $username)) {
  echo "Valid username";
} else {
  echo "Username must be 3-20 characters and alphanumeric.";
}
?>

โœ… Best Practices

  • Never trust client-side validation alone
  • Use htmlspecialchars() before outputting user data
  • Validate data type, length, and structure
  • Use a central validation function or library for consistency

๐Ÿ“„ Full Example

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
  $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die('Invalid email');
  }
  echo "Hello, " . htmlspecialchars($name);
}
?>
Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
25
1
0
Join Our OBS Community

Loading...

Join Now