How can I properly escape HTML form input default values in PHP?

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.


Solution 1:

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

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

Solution 2:

htmlspecialchars would work in both cases. Have a look at the different flag options to avoid quotation marks being a problem in the input case.

Solution 3:

Given it is kinda long I would put it in a function

<?PHP
function encodeValue ($s) {
    return htmlentities($s, ENT_COMPAT|ENT_QUOTES,'ISO-8859-1', true); 
}
?>

This has ENT_QUOTES to make sure single and double quotes are encoded, but it will also encode special characters (Like in José) instead of inserting an empty string.

Then you can do:

<input type="text" name="firstname" value="<?= encodeValue($_POST['firstname']) ?>" />

and

<textarea name="content"><?= encodeValue($_POST['content']) ?></textarea>