Do I need to sanitize user-inputted data, before s

2019-02-16 13:06发布

问题:

I have a form in which I accept name, email and message from a user. I do the validation for name, email and message and just send it using the mail() function.

If I was inputting the $name, $email and $message in a database, I would escape this data for SQL injection; or, if I was echoing it out on a webpage, I would use htmlspecialchars().

What should I do when I am sending this data in a email? I know I don't have to worry about SQL injection, but what about XSS? Should I use htmlspecialchars() on these three variables too?

I send the mail like this:

mail('admin@mywebsite.com', 'Contact From: '. $name, "$message", 'From: '. $email);

I have read about email injection, but I can't understand it.

Please let me know about this.

回答1:

The escaping entirely depends on the context the data is embedded into.

Are you sending HTML mails? Then you have HTML context, and htmlspecialchars() must be used.

If you are sending plain text mails, there is no escaping for plain text.

The only threat would be that your mail client has some bug that interprets the plain text as something executable and then acts up when you get some strange names and mail adresses.

But this only applies to the mail's content, not the actual headers.

You are using a custom mail header From. Do not use this. From is used in spam filters. If I would enter my mail address, and you are sending this mail with From: my@mail, you are impersonating my own email server. Spam used to use this to hide the real source, and to redirect complaints and error feedback to the unhappy guy behind that mail address. Because of this today there are mechanisms that will prevent such abuse. So just do not pretend I am sending this mail - YOU do.

If you want to be able to answer me with a click on the reply button, use the Reply-to header, but always use From: dont-answer@YOURWEBSITE.example.

Additionally, these custom headers are the entry point for bad things. Make sure you are only adding mail addresses. Make sure you do not add any line feed characters. These would make the mailserver think that there is a new header coming up, and this might lead to mail header injection.



回答2:

you need to validate the email address to make sure it singular and not multiple addresses to stop email spamming

http://www.php.net/manual/en/filter.filters.validate.php

$email = "email@me.com";

 if(!filter_var($email, FILTER_VALIDATE_EMAIL))
   {
   echo "email not valid"; //  do not send
   }
 else
   {
   echo "email valid"; // send
   }


回答3:

The problem is simple. If some user can send someone else a email he could use HTML or JavaScript wich is interpreted in most Email-Clients and every webmail interface to rewrite the contents. He could insert a iFrame loading another site or injecting a PopUp Script.

Its most important to sanitize the input the way you would sanitize it for a Browser.