What are the best practices for handling user input in PHP to ensure data integrity and security?

To ensure data integrity and security when handling user input in PHP, it is important to validate and sanitize the input before using it in any database queries or displaying it on a webpage. This can help prevent SQL injection attacks, cross-site scripting (XSS) attacks, and other vulnerabilities.

// Validate and sanitize user input
$username = isset($_POST['username']) ? filter_var($_POST['username'], FILTER_SANITIZE_STRING) : '';
$email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) : '';

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();