I have a profile page in which I want to display informations from the database for most users, and a form with the current data as default value for the users with modification rights.
if ($IDprofile == $_SESSION['userID'])
{
echo "<form method='post'>
Surname: <input type='text' required name='surname' maxlength=50
value=".htmlentities($user['Surname'])."><br>
Name: <input type='text' required name='name' maxlength=50
value=".htmlentities($user['Name'])."><br>
Birthdate (format YYYY-MM-DD): <input type='text' required name='BirthDate' value='";
if ($user['BirthDate'] != null)
echo $user['BirthDate'];
else
echo "-";
echo "'><br>
Description: <input type='text' maxlength=255 name='description' value='";
if ($user['Description'] != null)
echo htmlentities($user['Description']);
else
echo "-";
echo "'><br>
<input type='submit' value='OK'></form>";
}
As you can see, I tried with htmlentities
, which should transform the apostrophe into '
, but it doesn't work. Other methods like addslashes
and addcslashes
don't work either.
What is displayed is my form input with the value it should have, until the place where there should be an apostrophe, where it just ends. addslashes
does the same, with a /
before the end.
What puzzles me the most is that I have a surname with an apostrophe in it in my database, and this one is displayed just fine.
htmlentities
by default only encodes "
double quotes, because those are the more common terminators for HTML attributes. If you want it to encode '
single quotes too, you need to set the ENT_QUOTES
flag:
htmlentities($foo, ENT_QUOTES | ENT_HTML401)
(ENT_HTML401
is the other default flag; these days you may want to use ENT_HTML5
instead.)
You should also actually delimit your attributes with quotes! Currently your result looks like value=James
, which isn't incorrect, but will get you into trouble once your values contain spaces or, well, quotes or other special characters.