Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping double quotes in a value for a sticky form in PHP

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?

like image 978
VirtuosiMedia Avatar asked Nov 28 '22 19:11

VirtuosiMedia


2 Answers

You want htmlentities().

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

like image 180
Greg Avatar answered Dec 06 '22 06:12

Greg


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.

like image 24
thesmart Avatar answered Dec 06 '22 06:12

thesmart