security.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /**
  3. * 安全防范
  4. * 进行sql注入过滤,xss过滤和csrf过滤
  5. *
  6. * 令牌调用方式
  7. * 输出:直接在模板上调用getToken
  8. * 验证:在验证位置调用checkToken
  9. *
  10. * @package
  11. */
  12. defined('InShopNC') or exit('Access Invalid!');
  13. class Security{
  14. /**
  15. * 取得令牌内容
  16. * 自动输出html 隐藏域
  17. *
  18. * @param
  19. * @return void 字符串形式的返回结果
  20. */
  21. public static function getToken(){
  22. $token = encrypt(TIMESTAMP,md5(MD5_KEY));
  23. echo "<input type='hidden' name='formhash' value='". $token ."' />";
  24. }
  25. public static function getTokenValue(){
  26. return encrypt(TIMESTAMP,md5(MD5_KEY));
  27. }
  28. /**
  29. * 判断令牌是否正确
  30. *
  31. * @param
  32. * @return bool 布尔类型的返回结果
  33. */
  34. public static function checkToken(){
  35. $data = decrypt($_POST['formhash'],md5(MD5_KEY));
  36. return $data && (TIMESTAMP - $data < 5400);
  37. }
  38. /**
  39. * 将字符 & " < > 替换
  40. *
  41. * @param unknown_type $string
  42. * @return unknown
  43. */
  44. public static function fliterHtmlSpecialChars($string) {
  45. $string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
  46. str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
  47. return $string;
  48. }
  49. /**
  50. * 参数过滤
  51. *
  52. * @param array 参数内容
  53. * @param array $ignore 被忽略过滤的元素
  54. * @return array 数组形式的返回结果
  55. *
  56. */
  57. public static function getAddslashesForInput($array,$ignore=array()){
  58. if (!function_exists('htmlawed')) require(BASE_CORE_PATH.'/framework/function/htmlawed.php');
  59. if (!empty($array)){
  60. while (list($k,$v) = each($array)) {
  61. if (is_string($v)) {
  62. if (get_magic_quotes_gpc()) {
  63. $v = stripslashes($v);
  64. }
  65. if($k != 'statistics_code') {
  66. if (!in_array($k,$ignore)){
  67. //如果不是编辑器,则转义< > & "
  68. $v = self::fliterHtmlSpecialChars($v);
  69. } else {
  70. $v = htmlawed($v,array('safe'=>1));
  71. }
  72. if($k == 'ref_url') {
  73. $v = str_replace('&amp;','&',$v);
  74. }
  75. }
  76. $array[$k] = addslashes(trim($v));
  77. } else if (is_array($v)) {
  78. if($k == 'statistics_code') {
  79. $array[$k] = $v;
  80. } else {
  81. $array[$k] = self::getAddslashesForInput($v);
  82. }
  83. }
  84. }
  85. return $array;
  86. }else {
  87. return false;
  88. }
  89. }
  90. public static function getAddSlashes($array){
  91. if (!empty($array)){
  92. while (list($k,$v) = each($array)) {
  93. if (is_string($v)) {
  94. if (!get_magic_quotes_gpc()) {
  95. $v = addslashes($v);
  96. }
  97. } else if (is_array($v)) {
  98. $array[$k] = self::getAddSlashes($v);
  99. }
  100. }
  101. return $array;
  102. }else {
  103. return false;
  104. }
  105. }
  106. }