How to Properly Escape HTML Form Input Default Values in PHP

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.

HTML/PHP - default input value

You need to check the return of get_option first, and substitute something if a default is not available

<?php
$default = get_option('your_name');
if( $default == "")
{
$default = <whatever your default value is>;
}
?>
<input type="text" name="your_name" value="<?php echo $default; ?>" />

Change get_option to return an empty string (or something else) if the default is not available.

How do I escape quotes for HTML input (using PHP)?

All user-inputted data that is being output within HTML attributes should be run through htmlspecialchars. This encodes quotes and other characters:

echo '<input value="'.htmlspecialchars($lmao).'" name="lmao" type="text">';

PHP: How to escape HTML form input multidimensional keys

You can use urlencode to escape the $attr value, and then use array_walk over $_POST['key'] to replace the keys with their urldecode version:

if (isset($_POST['key'])) {
array_walk($_POST['key'], function (&$a) {
$a = array(urldecode(key($a)) => current($a));
});
}
var_dump($_POST);

$attr = '//*[self::textarea or self::input]/@placeholder';
?>
<form action="" method="post">

<input type="text" name="key[1][<?php echo urlencode($attr);?>]">

<input type="submit" value="Submit">
</form>

Output:

array(1) {
["key"]=>
array(1) {
[1]=>
array(1) {
["//*[self::textarea or self::input]/@placeholder"]=>
string(3) "asd"
}
}
}

If you have multiple elements under each numeric key value, you will need to use a foreach within the array_walk:

if (isset($_POST['key'])) {
array_walk($_POST['key'], function (&$a) {
foreach ($a as $key => $value) {
$a[urldecode($key)] = $value;
unset($a[$key]);
}
});
}

How can i pervent special character input to a php file?

You may use htmlspecialchars, that's what that function is for.

Check the manual.

Here's an example from the manual:

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?>

Just add the string to the 1st argument of the function. The 2nd will tell the function how to handle quotes. In the example above, it will convert both double and single quotes.

Do I need to escaping html output in input field?

Do I need to escaping html output in input field?

Yes, every input must be escaped. Especially if it comes from the user. You should never ever trust user's input.

htmlspecialchars has some sort of a bug where you can't directly include strings in it's second and third parameter. Therefore a workaround is needed.
As of PHP 5.4+ the default charset is UTF-8 before that it was ISO-8859-1

ENT_IGNORE Will just drop all invalid code. This is bad for two reasons: First, you won’t notice invalid encoding, because it will be simply dropped. Second, this imposes a certain security risk

ENT_SUBSTITUTE Is a new alternative option which has more sensible approach at the problem: Instead of just dropping the code units they will be replaced by a Unicode character (U+FFFD). So invalid code unit sequences will be replaced by � characters.

/**
* htmlspecialchars fix|hack. Well done PHP, well done...
*/
define('CHARSET', 'UTF-8');
define('REPLACE_FLAGS', ENT_QUOTES | ENT_SUBSTITUTE);

function filter($string = null)
{
return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
}

For more information how to prevent XSS, SQL injection see these links:
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?

Escaping output safely for both html and input fields

I'm sorry but I cannot reproduce the behaviour you describe. I've always used htmlspecialchars() (which does essentially the same task as htmlentities()) and it's never lead to any sort of double-encoding. The page source shows déjà vu in both places (of course! that's the point!) but the rendered page shows the appropriate values and that's what sent back to the server.

Can you post a full self-contained code snippet that exhibits such behaviour?

Update: some testing code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>

<?php

$default_value = 'déjà vu <script> ¿foo?';

if( !isset($_GET['foo']) ){
$_GET['foo'] = $default_value;
}

?>

<form action="" method="get">
<p><?php echo htmlentities($_GET['foo']); ?></p>
<input type="text" name="foo" value="<?php echo htmlentities($_GET['foo']); ?>">
<input type="submit" value="Submit">
</form>

</body>
</html>

Answer to updated question

The htmlentities() function, as its name suggests, is used when generating HTML output. That's why it's of little use in your second example: JavaScript is not HTML. It's a language of its own with its own syntax.

Now, the problem you want to fix is how to generate output that follows these two rules:

  1. It's a valid string in JavaScript.
  2. It can be embedded safely in an HTML document.

The closest PHP function for #1 I'm aware of is json_encode(). Since JSON syntax is a subset of JavaScript, if you feed it with a PHP string it will output a JavaScript string.

As about #2, once the browser enters a JavaScript block it expects a </script> tag to leave it. The json_encode() function takes care of this and escapes it properly (<\/script>).

My revised test code:

<?php

$default_value = 'déjà vu </script> ¿foo?';

if( !isset($_GET['foo']) ){
$_GET['foo'] = $default_value;
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
$(function(){
$("input[type=text]").val(<?php echo json_encode(utf8_encode($_GET['foo'])); ?>);
});
//--></script>
</head>
<body>


<form action="" method="get">
<p><?php echo htmlentities($_GET['foo']); ?></p>
<input type="text" name="foo" value="(to be replaced)">
<input type="submit" value="Submit">
</form>

</body>
</html>

Note: utf8_encode() converts from ISO-8859-1 to UTF-8 and it isn't required if your data is already in UTF-8 (recommended).

How to escape insecure content in form in order to prevent XSS?

You should HTML encode the text, so that it ends up like this:

<input type="text" value="'test' "test" <script>alert('hacked');</script>" />

You should use the server language to do this. There is no built in support for this in Javascript, so you would have to build a function for that yourself.

In ASP.NET MVC for example it could look like this:

<input type="text" value="<%= Server.HtmlEncode(Model.UserInput) %>" />

MVC 2 also has the <%: %> tag that automatically encodes the text:

<input type="text" value="<%: Model.UserInput %>" />

Edit:

Examine the source of the page in the browser to see what the result is.

It looks like you are escaping the text twice, so that for example " is escaped into " and then into &quot;.

How to properly escape password field on HTML form?

No, htmlspecialchars would not produce a totally different password. It would produce value="> yeah" which, when parsed by the browser, is read as > yeah. Password fields are not in any way special in the treatment of special or non-special characters.

How to escape hidden form values in PHP

Attribute values are HTML text. Use htmlspecialchars.



Related Topics



Leave a reply



Submit