利用smarty escape函数防止XSS攻击

XSS攻击常见手段就是在输入的内容框中添加脚本来执行操作,比如获取用户的cookie,提交到自己的网站中。
Smarty模板中有escape函数,http://fising.cn/docs/Smarty_3_Manual_zh_cn/language.modifier.escape.html
它和JS中的escape()函数很像,但是可以选择不同的参数。
默认的参数html只转换 & ” ‘ < > *,可以有效的防止script脚本注入。
<{$test|escape}>
官方手册给的例子是:
<{$test|escape:"html"}> escapes & ” ‘ < >
<{$test|escape:"htmlall"} {* escapes ALL html entities *} <{$test|escape:"url"} <{$test|escape:"quotes"} “>$test|escape:”hexentity”}
这种用法虽然可以屏蔽HTML但是每个变量后面都带带上|escape,给写程序带来麻烦。
下面介绍下本人开发中所使用的方法,也算有点偏门但挺实用
SMARTY 有个 default_modifiers 变量 官方解释是默认修正器变量
我们可以利用它来修正
在显示页面前先执行
$smarty->default_modifiers = array(‘$’ => ‘escape:”html”‘);
这样所有以$开头的SMARTY变量都被处理了
同时我们也可以
$smarty->default_modifiers = array(‘$’ => ‘escape:”html”‘,’foreach’=> ‘smarty:”nodefaults”‘,’section’=> ‘smarty:”nodefaults”‘);
这么一来页面上$开头的变量都被转义,那有些变量我们需要html怎么办呢
<{$test|smarty:nodefaults}>
smarty:nodefaults可以让变量免除于默认修正器,这样就能使用html显示了

发表评论

电子邮件地址不会被公开。 必填项已用*标注


*