What are best practices for handling user input in PHP to prevent issues like SQL injection or cross-site scripting?

To prevent SQL injection in PHP, it is best practice to use parameterized queries with prepared statements when interacting with a database. This helps to sanitize user input and avoid malicious SQL injection attacks. Additionally, to prevent cross-site scripting (XSS) attacks, user input should be properly validated and sanitized before being displayed on a webpage.

// Preventing SQL Injection with prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Preventing Cross-Site Scripting (XSS) attacks
$clean_input = htmlspecialchars($_POST['input'], ENT_QUOTES, 'UTF-8');
echo $clean_input;