开发者

Escaping Characters in Email with PHP/MYSQL

I'm having a problem figuring out the logic behind how characters are being escaped when I use the mail() function for PHP. I'm using PHP 5.2, with magic_quotes_qpc ON and runtime/sybase OFF. Here's the problem.

  1. A have a form that takes a text input and I use mysqli_real_escape to escape special characters for use in an SQL statement like such:

    $text = mysqli_real_escape_string($dbc, $_GET['text']);
    
  2. If I type the following comment "I wouldn't eat that!" into the form, I see the following in database - "I wouldn\'t eat that!", which is what开发者_运维问答 I would expect. If I add carriage returns/new lines all I see in the database field in phpMyAdmin is the carriage return and newline with no special characters (i.e. no "\r\n" or anything like that).

  3. When I use the mail function to send a message (i.e. mail($to, $subject, $text, $headers)) I have been getting something weird like this in the email body:

    I wouldn\\\'t eat that\r\nI couldn\\\'t eat that
    

At the end of the day I just want the email output to be formatted exactly like the form input, in other words:

I wouldn't eat that
I couldn't eat that

I'm not sure why there is a triple escape before the apostrophe and why the \r\n is showing up in my email.


Magic quotes are bad. Don't use them.

http://www.php.net/manual/en/security.magicquotes.whynot.php

If you're using magic quote and mysqli_real_escape_string, then that explains why the strings are doubly escaped.

$text = mysqli_real_escape_string($dbc, $_GET['text']); // $_GET['text'] is already escaped

...

mail($to, $subject, $text, $headers); // Now $text contains a doubly escaped string

Turn off magic quotes (ensure you're app can handle that) and only escape when inserting into database (if using parameterized queries, i.e., PDO or mysqli, no need to ever escape!).

As a last resort, you can try using stripslashes on the string.


When retrieving results from the MySQL database, you need to use stripslashes() on the output or they will still contain the escaping slashes, for some reason.

Edit:

Then, you can do $theOutput = str_replace("\\r\\n", "\r\n", $theOutput); to fix the newlines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜