What are the best practices for handling user input in PHP to prevent vulnerabilities such as SQL injection or cross-site scripting?

To prevent vulnerabilities such as SQL injection or cross-site scripting in PHP, it is crucial to sanitize and validate user input before using it in any database queries or outputting it to the browser. This can be achieved by using prepared statements for database queries and escaping output using functions like htmlspecialchars().

// Example of using prepared statements to prevent SQL injection

// Establish database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind parameters
$stmt->bindParam(':username', $_POST['username']);

// Execute the statement
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll();

// Example of using htmlspecialchars() to prevent cross-site scripting
echo "Welcome, " . htmlspecialchars($_POST['username']) . "!";