How can I properly escape HTML form input default values in PHP?
Use htmlspecialchars($_POST['firstname'])
and htmlspecialchars($_POST['content'])
.
Always escape strings with htmlspecialchars()
before showing them to the user.
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.
Given it is kinda long I would put it in a function
<?PHPfunction 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>