nl2br function not working with mysql_real_escape_string
Started on the old forum in April 2012 · view the original in the archive · old links redirect here
it wont work as mysql_escape_string adds a \ so use: $text = str_replace("\r\n", " ", $text);
actually i am using this function
function protect($val)
{
$val = mysql_real_escape_string($val);
$val = trim($val);
$val = htmlspecialchars($val);
$val = stripslashes($val);
return $val;
}
as i am using stripslashes() i just vanished \ option. thats why I am getting only rn. no backslash. 🙁
something else wrote: and what happens when someone posts this code? 1' OR WHERE email!='1 lol
converted all ' to ’ . I guess. is that ok or what? please reply.
First of all you're getting everything mixed up. I really can't see any reason those three functions (htmlspecialchars, mysql_real_escape_string, stripslashes) are in one function, as they are meant to perform different tasks that are scarcely related. Before I give you a more concise function I think you should know that the htmlspecialchars function, as the name implies, is meant to escape content that maybe otherwise seen as HTML by the browser as plain text NOT when submitting to the database. htmlspecialchars should be called correctly when polling data from the database that might potentially contain html data you don't want rendered. In other words, I'll only use htmlspecialchars when I'm displaying data already saved in the database, I wouldn't use htmlspecialchars to escape data when saving to database.
function db_string_escape($string, $weak_escape = FALSE)
{
// Check if magic quotes is enabled
$_magic_quotes = (bool) get_magic_quotes_gpc();
if ($_magic_quotes === TRUE)
{
// We don't want magic quotes adding extra slash
$string = stripslashes($string);
}
// we can go on and escape properly
return $weak_escape ? addslashes($string) : mysql_real_escape_string($string);
}
Added after 6 minutes:
Your nl2br should work just fine now, I'm guessing you call it after polling data from database?! And also that ...
// This should work...
$string = nl2br(htmlspecialchars($string));
// This Won't Work
$string = htmlspecialchars(nl2br($string));