How to properly escape html form input default values in php?

Ryan picture Ryan · Jun 6, 2011 · Viewed 97.3k times · Source

Given the following two html/php snippets:

<input type="text" name="firstname" value="<?php echo $_POST['firstname']; ?>" />

and

<textarea name="content"><?php echo $_POST['content']; ?></textarea>

what character encoding do I need to use for the echoed $_POST variables? Can I use any built in PHP functions? Please assume that the $_POST values have not been encoded at all yet. No magic quotes no nothing.

Answer

rid picture rid · Jun 6, 2011

Use htmlspecialchars($_POST['firstname']) and htmlspecialchars($_POST['content']).

Always escape strings with htmlspecialchars() before showing them to the user.