What are the best practices for securely handling and displaying user-generated content in PHP websites?

When handling user-generated content in PHP websites, it is crucial to sanitize and validate input to prevent SQL injection, cross-site scripting (XSS), and other security vulnerabilities. Use PHP functions like htmlspecialchars() to escape special characters and prevent XSS attacks. Additionally, consider implementing content moderation and user authentication to ensure that only authorized users can submit content.

// Sanitize user input using htmlspecialchars() to prevent XSS attacks
$user_input = htmlspecialchars($_POST['user_input']);

// Validate user input to prevent SQL injection
if (preg_match('/^[a-zA-Z0-9\s]+$/', $user_input)) {
    // Proceed with processing the sanitized input
} else {
    // Handle invalid input error
    echo "Invalid input. Please try again.";
}