From a form, I’m asking the user to enter some text. I will retrieve this text using $_POST['text'].
The user enters the string “It’s my text!”
$newText = mysql_real_escape_string($_POST['text']);
Now on the very same page after I’ve inserted $newText into the database I want to display
the text to the user and also use it as the value of an input text box using PHP.
// I want to make sure the user hasn't added any unsafe html in their string
$newText = htmlentities($newText);
echo "You've entered: " . $newText . "<br />";
echo "<form action=someaction.php method=post>";
echo "<input type=text value=\"" . $newText . "\">";
echo "</form>";
The output is:
You've entered: It\'s my text!
[It\'s my text!]
How do I avoid these slashes, and should I be doing anything else with my data?
You’re passing the text through
mysql_real_escape_string()which, as the name suggests, escapes the string, including apostrophes.mysql_real_escape_string()is meant only for preparing the data for saving to database. You shouldn’t use it when displaying data to the user.So, the solution is simple: remove the line and use
htmlentities()only. Usemysql_real_escape_string()when you’re saving the string to database (and only then).