Slath Slath - 2 years ago 70
PHP Question

How to escape apostrophe inside an input made with apostrophes

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
Name: <input type='text' required name='name' maxlength=50

Birthdate (format YYYY-MM-DD): <input type='text' required name='BirthDate' value='";
if ($user['BirthDate'] != null)
echo $user['BirthDate'];
echo "-";
echo "'><br>

Description: <input type='text' maxlength=255 name='description' value='";
if ($user['Description'] != null)
echo htmlentities($user['Description']);
echo "-";
echo "'><br>
<input type='submit' value='OK'></form>";

As you can see, I tried with
, which should transform the apostrophe into
, but it doesn't work. Other methods like
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.
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download