tags:

views:

41

answers:

2

hi there, so i use mysql_real_escape_string to sanitize some user input before entering it into the db, i would like to know how do i go about "reversing" this function so that when i output to the screen all escaped characters like /n /r get converted to actual new lines...thanks!

also, what is the difference between /n and /r?

+1  A: 

stripslashes($variableHere) will remove any slashes from the $variableHere, it should only be used if there are slashes in the string. mysql_real_escape_string() preserves the intial string, so whatever you pass it is what will be entered into the database. See the php.net manual attached below for more information.

As far as your example of the \n and \r characters, they will be preserved by mysql_real_escape_string() in their natural state, but if you echo \n and \r directly into HTML it won't show the linebreak, you'll have to use nl2br($string) for that result.

http://php.net/manual/en/function.stripslashes.php

http://php.net/manual/en/function.nl2br.php

edit Cleaning this up as apparently it's hard to understand.

Robert
He doesn't **need** anything but the `nl2br()` function for his question, but I provided him the stripslashes and the link to the manual explaining.
Robert
I didn't tell him to run that command on everything coming out of a database, stop acting like I did. I said it will remove any slashes, if he isn't seeing any slashes output, there's no reason to run the command.
Robert
A: 

mysql_real_escape_string() doesn't add slashes to stored data. It escapes characters so they can be passed safely through the mysql engine. The data is stored as is, without slashes.

As such you don't need to use stripslashes() when outputting from the database any data escaped with them.

If you're seeing extra slashes it's because you're either adding them somewhere, with say addslashes() or magic_quotes_gpc() is turned on.

As has been noted \r \n are not escaped they are line breaks. Only use stripslashes() on data that has escape slashes included or you risk removing essential slashes.

Edited to add: The only time you'd want to strip slashes from mysql_real_escape_string() is if you did so before storing data, say if you for some reason escaped data the minute you got it from a form then echoed it out in an error message/pre-populated form field.

*The only time you'd want to strip slashes from `mysql_real_escape_string()` is...* Don't do this. `mysql_real_escape_string()` should only be used immediately before querying because it's executed specifically for the active database connection. Use a different escape / sanitizer if you need that type of functionality elsewhere in your code.
banzaimonkey