Home >Backend Development >PHP Tutorial >How to Sanitize User Input Before Mailing in PHP?
When developing PHP mailer scripts, it's crucial to ensure the security of user-submitted data before mailing it. Neglecting input sanitization leaves your script vulnerable to vulnerabilities like cross-site scripting (XSS) and SQL injection.
To address this challenge, the following code demonstrates how to sanitize user input using the filter_var() function:
<code class="php">$to = "[email protected]"; $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING); $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING); $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); $body = "Person $name submitted a message: $message"; $subject = "A message has been submitted"; $headers = 'From: ' . $email; mail($to, $subject, $body, $headers); header("Location: http://example.com/thanks");</code>
The filter_var() function provides various sanitizer filters. In this case, we apply the FILTER_SANITIZE_STRING filter to name and message to remove malicious characters. For email, we use FILTER_SANITIZE_EMAIL to validate the email address.
By implementing input sanitization, you can enhance the security of your mailer script and protect it from potential vulnerabilities.
The above is the detailed content of How to Sanitize User Input Before Mailing in PHP?. For more information, please follow other related articles on the PHP Chinese website!