我有一个简单的问题:什么时候最好清理用户输入?其中哪一项被认为是最佳实践:
例如,使用HTML::entities()并将结果保存到数据库.或者通过HTML在视图中使用方法,因为在这种情况下,laravel默认使用HTML::entities().或者也许通过使用两者.
编辑:我找到了有趣的例子http://forums.laravel.com/viewtopic.php?id=1789.还有其他方法可以解决这个问题吗?
Erl*_*end 12
我会说你需要两个地点,但原因各不相同.当数据进入时,您应该根据域验证数据,并拒绝不符合要求的请求.例如,如果您期望一个数字,则允许标记(或该文本的文本)是没有意义的.对于表示年份的参数,您甚至可能希望检查它是否在某个范围内.清理开始自由文本字段.您仍然可以对0字节等意外字符进行简单验证.恕我直言,最好通过安全sql(参数化查询)存储原始,然后正确编码输出.有两个原因.首先,如果您的清洁剂有错误,您如何处理数据库中的所有数据?重新组合会产生不良后果.其次,对于您使用的输出(JSON,HTML,HTML属性等),您希望进行上下文转义.
我在Laravel中有一篇关于输入过滤的完整文章,您可能会发现它很有用http://usman.it/xss-filter-laravel/,这里是本文的摘录:
您可以自己进行全局XSS清理,如果您没有库来编写您可能经常需要的常用方法,那么我请您在应用程序/库中创建一个新的库Common.将这两种方法放在公共库中:
/*
* Method to strip tags globally.
*/
public static function global_xss_clean()
{
// Recursive cleaning for array [] inputs, not just strings.
$sanitized = static::array_strip_tags(Input::get());
Input::merge($sanitized);
}
public static function array_strip_tags($array)
{
$result = array();
foreach ($array as $key => $value) {
// Don't allow tags on key either, maybe useful for dynamic forms.
$key = strip_tags($key);
// If the value is an array, we will just recurse back into the
// function to keep stripping the tags out of the array,
// otherwise we will set the stripped value.
if (is_array($value)) {
$result[$key] = static::array_strip_tags($value);
} else {
// I am using strip_tags(), you may use htmlentities(),
// also I am doing trim() here, you may remove it, if you wish.
$result[$key] = trim(strip_tags($value));
}
}
return $result;
}
Run Code Online (Sandbox Code Playgroud)
然后将此代码放在before filter的开头(在application/routes.php中):
//Our own method to defend XSS attacks globally.
Common::global_xss_clean();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22809 次 |
| 最近记录: |