Fast and Secure Web Apps |
|
2024-11-26 |
|
|
7 |
|
|
Common approach to treat user data for display purposes
Safe Form Handling
<form action="<?php echo htmlspecialchars($PHP_SELF, ENT_QUOTES)?>" method="POST">
Your name: <input type="text" name="name" /><br>
You age: <input type="text" name="age" /><br>
<input type="submit" />
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST') {
$Oname = htmlspecialchars($_POST['name'], ENT_QUOTES);
$Oage = (int)$_POST['age'];
echo "Hi $Oname, you are $Oage years old.";
}?>
We probably all know how braindead Internet Explorer is about how it deals with mime types, but it
is just as braindead in how it handles character set detection. If you don't specify a character set in
the Content-Type response header or in the page itself in an http-equiv META tag, it will scan the first
4096 bytes of the reponse body looking for bytes it recognizes as a specific character set. So the above
form which is safe on all other browsers is not safe on IE for input like this:
%2BADw-script%2BAD4-alert(document.cookie)%2BADw-/script%2BAD4-
This is the string: <script>alert(document.cookie)</script> written
in UTF-7 with + converted to %2B.
For PHP you can get around this by specifying a default charset in your php.ini file.
For non-PHP requests, you can use Apache's AddDefaultCharset configuration
directive which will add the specified charset to any response that does not specify one
already. If you simply turn it on, instead of specifying a charset you get Apache's
internal default of iso-8859-1.