How can PHP scripts be optimized to prevent code injection vulnerabilities when handling user input?

To prevent code injection vulnerabilities when handling user input in PHP scripts, it is crucial to sanitize and validate all incoming data. This can be achieved by using functions like htmlspecialchars() to encode user input before displaying it on the page and prepared statements when interacting with a database to prevent SQL injection attacks.

$user_input = $_POST['user_input'];
$sanitized_input = htmlspecialchars($user_input);
// Use $sanitized_input in your code to prevent code injection vulnerabilities