View Full Version : \r and \n showing up after POSTing user submitted text

12-20-2007, 05:18 PM
I have a textarea on a page that POSTs to itself and then inserts into my MySQL database. I put that text into a variable and do a mysql_real_escape_string() on it. The problem I'm running into is this: if there is an error with the page, it puts the contents of the escaped variable back into the textarea, and those contents now have escaped quotes and \r and \n in them. How do I reverse these changes when I put the content back into the textarea?


In textarea, the user inputs:

This isn't mine.
But this is.

After this input is POSTed into a variable and escaped, and there is an error on the page, this escape input is put back into the textarea and now shows this:

This isn\'t mine.\r\nBut this is.

12-20-2007, 06:40 PM
Run the value through stripslashes() and nl2br(), and perhaps html_entity_decode() as well.

12-20-2007, 08:51 PM
That will fix quotes and HTML in a string just fine, but it doesn't fix the \r\n problem. When I use stripslashes() and nl2br(), the string becomes:

This isn't mine.rnBut this is.

In other words, after mysql_real_escape_string(), it makes the carriage return (new paragraph) into a \r\n instead of an actual return in the textarea. So how do I change the \r\n back to a carriage return?

12-20-2007, 09:15 PM
Only apply the escaping to the string that is about to enter the database. Not your raw data.

12-20-2007, 09:25 PM
Why didn't I think of that? lol Thanks aedrin!

I was putting the input into a variable and then doing the mysql_real_escape_string() on that same variable, and then echoing it in the textarea. But what I've done now is still put the input into the variable, but then create another variable with $db_ at the beginning that actually goes into the database. Works a charm!

12-20-2007, 09:26 PM
You couldn't see the forest through the trees. :p