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.
For escaping data to use within an HTML body context, use Laminas\Escaper\Escaper 's escapeHtml() method. Internally it uses PHP's htmlspecialchars() , correctly setting the flags and encoding for you.
Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.
The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.
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
<?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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With