How can email header injection be prevented in PHP form mailers?
Email header injection can be prevented in PHP form mailers by sanitizing user input to ensure that it does not contain any additional headers. This can be done by using functions like `filter_var()` or `htmlspecialchars()` to escape special characters. Additionally, setting the `Content-Type` header explicitly can help prevent injection attacks.
// Sanitize user input to prevent email header injection
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars($_POST['message']);
// Set the Content-Type header to prevent injection attacks
$headers = "Content-Type: text/plain; charset=UTF-8";
// Send the email using the sanitized input and headers
mail($email, "Subject", $message, $headers);
Related Questions
- Are there best practices for using XPath in PHP to retrieve multiple tag elements?
- How can PHP functions like glob, mkdir, and move_uploaded_file be used to automate folder creation based on XML data?
- What are some best practices for ensuring smooth transition to newer PHP versions, particularly when dealing with legacy scripts and applications?