In what ways can the misuse of external variables in PHP scripts lead to security vulnerabilities, and how can developers mitigate these risks?

Misuse of external variables in PHP scripts can lead to security vulnerabilities such as SQL injection, cross-site scripting (XSS), and remote code execution. Developers can mitigate these risks by properly sanitizing and validating user input before using it in their scripts.

// Example of mitigating SQL injection vulnerability by using prepared statements
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $_POST['username']);
$stmt->execute();