How can PHP developers ensure the security of their code when dealing with global variables and form input?
When dealing with global variables and form input in PHP, developers can ensure the security of their code by properly sanitizing and validating user input. This can be done by using functions like htmlspecialchars() to prevent XSS attacks and filter_input() to validate input against predefined rules. Additionally, developers should avoid directly accessing global variables and instead use superglobal arrays like $_POST and $_GET.
// Sanitize and validate form input
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
// Prevent XSS attacks by escaping output
echo htmlspecialchars($name);
echo htmlspecialchars($email);