1

I'm trying to use the php nl2br() function to convert \r\n characters into <br> tags in an email. There seems to be some sort of conflict when I try to use it with mysqli_real_escape_string(). I can verify seperately that the mysqli_real_escape_string function() is giving the proper output, and that the nl2br() function is properly converting the appropriate characters to <br> tags, but they won't work together. Why?!

I can confirm nl2br works:

    $message= "This\r\nis\n\ra\nstring\r";
    $message= nl2br($message);
    echo($message);

output:

"This is a string"

I can confirm mysqli_real_escape_string() works:

//assume $_POST['message'] = "this is a string"
$message = mysqli_real_escape_string($connection, $_POST['message']); 
echo($message);

output:

This\r\nis\n\ra\nstring\r

When I use them together:

$message = nl2br(mysqli_real_escape_string($connection, $_POST['message'])); 

Output:

This\r\nis\r\na\r\nstring
user2755541
  • 536
  • 2
  • 10
  • 25
  • Why would you use `nl2br` on a string returned by `mysqli_real_escape_string`? – PeeHaa Nov 10 '14 at 17:42
  • 1
    escaping should be the **LAST** operation you perform on a string. Doing further manipulations of an escaped string can actually UNDO the escaping and open you up to sql injection attacks again. – Marc B Nov 10 '14 at 17:58

1 Answers1

2

mysqli_real_escape_string escapes newlines, so nl2br can't find them (obviously).

A simple script to demonstrate this:

$ cat test.php
$c = mysqli_connect('192.168.33.10', 'root', '');
print("Hello\nWorld\n");
print(mysqli_real_escape_string($c, "Hello\nWorld"));

$ php test.php | hexdump -C  
00000000  48 65 6c 6c 6f 0a 57 6f  72 6c 64 0a 48 65 6c 6c  |Hello.World.Hell|
00000010  6f 5c 6e 57 6f 72 6c 64                           |o\nWorld|

As you can see, the newline character (0x0a) has been replaced by the string \n (0x5c and 0x6e).

So, call nl2br first:

$message = mysqli_real_escape_string(nl2br($_POST['message']), $connection);
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • That's working half way. So now it's creating the carriage return, but it's still keeping the /r/n at the beginning of each line. – user2755541 Nov 10 '14 at 17:58
  • Actually, I figured it out. I performed this function after escaping the string: $message = str_replace('\r\n','', $message); I ran into trouble with that... apparently there's a difference between using single and double quotes around the '\r\n'. "\r\n" doesn't work. – user2755541 Nov 10 '14 at 18:02
  • 1
    @user2755541 Yes, in PHP, only double-quoted (`"`) are parsed for variables & escape characters, single quoted strings (`'`) are not; see: http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php – Martin Tournoij Nov 10 '14 at 18:03