What are the potential pitfalls of not securely handling user input in PHP scripts, as seen in the provided code?

When user input is not securely handled in PHP scripts, it opens up the possibility of various security vulnerabilities such as SQL injection, cross-site scripting (XSS), and code injection attacks. To mitigate these risks, it is essential to properly sanitize and validate user input before using it in your code.

// Sanitize and validate user input before using it in the code
$username = isset($_POST['username']) ? filter_var($_POST['username'], FILTER_SANITIZE_STRING) : '';
$password = isset($_POST['password']) ? filter_var($_POST['password'], FILTER_SANITIZE_STRING) : '';

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute(array('username' => $username, 'password' => $password));

// Use htmlspecialchars to prevent XSS attacks when outputting user input
echo "Welcome, " . htmlspecialchars($username);