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

PhpHtmlFormsXss

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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

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

Solution 2 - Php

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 - Php

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanView Question on Stackoverflow
Solution 1 - PhpridView Answer on Stackoverflow
Solution 2 - PhpNiklasView Answer on Stackoverflow
Solution 3 - PhpEricView Answer on Stackoverflow