Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter/sanitizing email subject and body in PHP

I'm using PHPMailer to send emails.

Now, we all know we need to always check user input.
But how about the subject and body of emails? (so i do not mean the emailadress)

What does need to be sanitized and how to do it? What are the (major) vulnerability's?

Should i'll use something like HTMLPurifier for this? Because i want the user to be able to markup there emails. Or should i'll use/write a BB-code function what can be used?

Update:

For mail body:
I now use htmlspecialchars with ent_quotes flag on. After this ill run a BB-code (jBBCode) parser over the message. This one looks safe now.

For subject:
I do not use any validation/sanitizing/etc. (exept min and max strlen) on the subject field. Tested with some javascript but it looks like it's all okay.

Can i assume this is safe now? (P.s. the code does not get printed anywhere else than in the email.)

like image 471
Ramon Bakker Avatar asked Jan 01 '26 16:01

Ramon Bakker


2 Answers

Yes, you need to clean user input before sending. HTMLPurifier and HTMLawed make a fair job of sanitising, but need to be tuned to not block out useful stuff - both err on the side of caution. BBCode or markdown do make things much easier to filter, so long as you don't need to do intricate layouts.

like image 191
Synchro Avatar answered Jan 03 '26 04:01

Synchro


You can use

<?php
filter_var($body, FILTER_SANITIZE_FULL_SPECIAL_CHARS)

to help protect against special characters also you can use RAW such as

<?php
filter_var($body, FILTER_SANITIZE_RAW, FILTER_FLAG_ENCODE_HIGH)

Full details can be found here -> https://secure.php.net/manual/en/function.filter-var.php

like image 25
Michael Trimm Avatar answered Jan 03 '26 05:01

Michael Trimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!