What are the best practices for handling user-generated content in PHP to prevent security vulnerabilities?

When handling user-generated content in PHP, it is important to validate and sanitize the input to prevent security vulnerabilities such as SQL injection and cross-site scripting (XSS) attacks. Use functions like htmlspecialchars() to encode user input before displaying it on the page and prepared statements for database queries to prevent SQL injection.

// Validate and sanitize user input
$userInput = $_POST['user_input'];
$cleanInput = htmlspecialchars($userInput);

// Use prepared statements for database queries
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $cleanInput);
$stmt->execute();