views:

286

answers:

4

With PHP, which function is best to be used with $_GET[] values to make them browser safe?

I have read up on a few htmlspecialchars() and htmlentities(). Should one of those be used or is there another function that would work better?

+4  A: 

Using htmlspecialchars suffices to encode the HTML special characters. htmlentities is only necessary if you want to use characters that can not be encoded with the character encoding you are using.

But make sure to specify the quote_style parameter when you want to use the output in an attribute value quoted with single quotes like:

echo "<input type='text' value='".htmlspecialchars($_GET['foobar'], ENT_QUOTES)."'>";

And to specify the charset parameter when you’re using a character encoding other than ISO 8859-1:

echo htmlspecialchars($_GET['foobar'], ENT_QUOTES, 'UTF-8');
Gumbo
+1  A: 

htmlspecialchars() should be applied to every $_GET variable you output into your page.

svens
+2  A: 

You use htmlspecialchars() to display $_GET variables, and use urlencode() to encode them.

Alix Axel
A: 

If you're doing this just for safety (removing <script>'s etc) rather than because you need to make sure characters are encoded correctly (although that could definitely be a concern) it could be worth looking at strip_tags, which will remove tags entirely, rather than just encoding the < and > symbols. This is a bit nicer in some cases - <b>hello</b> will become just "hello", rather than having the tags converted to become visible.

PimTerry