我有一篇关于 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;
}
然后将此代码放在之前过滤器的开头(在 application/routes.php 中):
//Our own method to defend XSS attacks globally.
Common::global_xss_clean();