Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

forms

php

xss

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.

like image 276
Ryan Avatar asked Jun 06 '11 07:06

Ryan


People also ask

How do you escape input in HTML?

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.

What is the code used in PHP to get value from input types?

Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.

What is value in input HTML?

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.


3 Answers

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

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

like image 182
rid Avatar answered Nov 02 '22 02:11

rid


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.

like image 33
Niklas Avatar answered Nov 02 '22 02:11

Niklas


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>
like image 1
Eric Avatar answered Nov 02 '22 02:11

Eric