What are common pitfalls to avoid when writing PHP code?

One common pitfall to avoid when writing PHP code is using insecure input validation, which can lead to vulnerabilities such as SQL injection or cross-site scripting attacks. To mitigate this risk, always sanitize and validate user input before using it in your code.

// Example of sanitizing and validating user input
$userInput = $_POST['input'];

// Sanitize input to prevent SQL injection
$sanitizedInput = mysqli_real_escape_string($connection, $userInput);

// Validate input to ensure it meets specific criteria
if (preg_match("/^[a-zA-Z0-9]+$/", $sanitizedInput)) {
    // Input is valid, proceed with using it in your code
} else {
    // Input is invalid, handle error appropriately
}