How can PHP developers ensure that their code is secure when handling user input?

Developers can ensure that their PHP code is secure when handling user input by using input validation and sanitization techniques. This involves checking the data type, length, and format of user input to prevent common vulnerabilities such as SQL injection and cross-site scripting attacks. Additionally, developers should use prepared statements for database queries and escape user input when outputting it to the browser.

// Example of input validation and sanitization in PHP
$userInput = $_POST['user_input'];

// Validate input
if (filter_var($userInput, FILTER_VALIDATE_EMAIL)) {
    // Sanitize input
    $sanitizedInput = htmlspecialchars($userInput);

    // Use sanitized input in database query
    $stmt = $pdo->prepare("INSERT INTO users (email) VALUES (:email)");
    $stmt->bindParam(':email', $sanitizedInput);
    $stmt->execute();
} else {
    echo "Invalid email address";
}