mPHP核心框架——网站安全处理类的代码实现
[文章作者:磨延城 转载请注明原文出处: https://mo2g.com/view/99/ ]
这个网站安全处理类用的比较多的应该就是安全过滤safeGPC()还有还原输出restore了.理论上,基本上能有效的过滤掉大部分的注册机、机器人对网站的骚扰.
这个网站安全处理类用的比较多的应该就是安全过滤safeGPC()还有还原输出restore了。下边就简单的介绍一下:
1)safeGPC就是通过对字符串做简单的转换处理,防止恶意用户通过非法途径对数据库进行sql注入。
2)restore把经过转换的字符串还原回来。
3)getKey用于生成随机的验证码
4)getToken则生成加密令牌
理论上,3)跟4)的组合出来的验证机制,基本上能有效的过滤掉大部分的注册机、机器人对网站的骚扰。
/*
作者:moyancheng
创建时间:2012-03-01
最后更新时间:2014-01-11
*/
class safe {
public $string;
public $strKey;
public function __construct() {
$this->strKey = '';
}
//简单的过滤,防止get post cookie注入
public static function safeGPC() {
if(get_magic_quotes_gpc()) {
foreach($_GET as $key => $value) $_GET[$key] = htmlspecialchars(trim($value), ENT_QUOTES);
foreach($_POST as $key => $value) $_POST[$key] = htmlspecialchars(trim($value), ENT_QUOTES);
foreach($_COOKIE as $key => $value) $_COOKIE[$key] = htmlspecialchars(trim($value), ENT_QUOTES);
} else {
foreach($_GET as $key => $value) $_GET[$key] = addslashes(htmlspecialchars(trim($value), ENT_QUOTES));
foreach($_POST as $key => $value) $_POST[$key] = addslashes(htmlspecialchars(trim($value), ENT_QUOTES));
foreach($_COOKIE as $key => $value) $_COOKIE[$key] = addslashes(htmlspecialchars(trim($value), ENT_QUOTES));
}
}
//还原字符串
public static function restore($str) {
if(get_magic_quotes_gpc()) return htmlspecialchars_decode(stripcslashes($str));
else return htmlspecialchars_decode($str);
}
//随机生成验证码
public static function getKey() {
$string = 'abcdefghijklmnopqrstuvwxyz123567890';
$i = 5;
while($i) {
$index = rand(0,34);
$strKey .= $string[$index];
--$i;
}
return $strKey;
}
//生成令牌
public static function getToken() {
return md5(uniqid(rand(), true));
}
}
我来说两句: