views:

996

answers:

2

I'm having a little bit of trouble making a sticky form that will remember what is entered in it on form submission if the value has double quotes. The problem is that the HTML is supposed to read something like:

<input type="text" name="something" value="Whatever value you entered" />

However, if the phrase: "How do I do this?" is typed in with quotes, the resulting HTML is similar to:

<input type="text" this?="" do="" i="" how="" value="" name="something"/>

How would I have to filter the double quotes? I've tried it with magic quotes on and off, I've used stripslashes and addslashes, but so far I haven't come across the right solution. What's the best way to get around this problem for PHP?

+3  A: 

You want htmlentities().

<input type="text" value="<?php echo htmlentities($myValue); ?>">

Greg
Thanks, that did the trick. I don't know why I didn't think of that.
VirtuosiMedia
htmlspecialchars should be enough
troelskn
+2  A: 

The above will encode all sorts of characters that have html entity code. I prefer to use:

htmlspecialchars($myValue, ENT_QUOTES, 'utf-8');

This will only encode:

'&' (ampersand) becomes '&amp;'
'"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.
'<' (less than) becomes '&lt;'
'>' (greater than) becomes '&gt;'

You could also do a strip_tags on the $myValue to remove html and php tags.

thesmart
Also, make sure your text encoding is UTF-8 for the above. You can usually omit that last parameter in htmlspecialchars if you'd like.
thesmart