1. 二宝博客首页
  2. php

PHP防注入安全代码

PHP代码
  1. 简述:/*************************  
  2. 说明:  
  3. 判断传递的变量中是否含有非法字符  
  4. 如$_POST、$_GET  
  5. 功能:防注入  
  6. **************************/    
  7.   
  8.   
  9. //要过滤的非法字符   
  10. $ArrFiltrate=array(“‘”,“;”,“union”);   
  11. //出错后要跳转的url,不填则默认前一页   
  12. $StrGoUrl=“”;   
  13. //是否存在数组中的值   
  14. function FunStringExist($StrFiltrate,$ArrFiltrate){   
  15. foreach ($ArrFiltrate as $key=>$value){   
  16.   if (eregi($value,$StrFiltrate)){   
  17.     return true;   
  18.   }   
  19. }   
  20. return false;   
  21. }   
  22.   
  23. //合并$_POST 和 $_GET   
  24. if(function_exists(array_merge)){   
  25.   $ArrPostAndGet=array_merge($HTTP_POST_VARS,$HTTP_GET_VARS);   
  26. }else{   
  27.   foreach($HTTP_POST_VARS as $key=>$value){   
  28.     $ArrPostAndGet[]=$value;   
  29.   }   
  30.   foreach($HTTP_GET_VARS as $key=>$value){   
  31.     $ArrPostAndGet[]=$value;   
  32.   }   
  33. }   
  34.   
  35. //验证开始   
  36. foreach($ArrPostAndGet as $key=>$value){   
  37.   if (FunStringExist($value,$ArrFiltrate)){   
  38.     echo alert(\”非法字符\”);“;   
  39.     if (emptyempty($StrGoUrl)){   
  40.     echo history.go(-1);“;   
  41.     }else{   
  42.     echo window.location=\””.$StrGoUrl.“\”;“;   
  43.     }   
  44.     exit;   
  45.   }   
  46. }   
  47. ?>   
  48.   
  49. 保存为checkpostandget.php    
  50. 然后在每个php文件前加include(“checkpostandget.php“);即可   
  51.   
  52.   
  53.   
  54.   
  55. 方法2   
  56.   
  57. /* 过滤所有GET过来变量 */  
  58. foreach ($_GET as $get_key=>$get_var)   
  59. {   
  60. if (is_numeric($get_var)) {   
  61.   $get[strtolower($get_key)] = get_int($get_var);   
  62. else {   
  63.   $get[strtolower($get_key)] = get_str($get_var);   
  64. }   
  65. }   
  66.   
  67. /* 过滤所有POST过来的变量 */  
  68. foreach ($_POST as $post_key=>$post_var)   
  69. {   
  70. if (is_numeric($post_var)) {   
  71.   $post[strtolower($post_key)] = get_int($post_var);   
  72. else {   
  73.   $post[strtolower($post_key)] = get_str($post_var);   
  74. }   
  75. }   
  76.   
  77. /* 过滤函数 */  
  78. //整型过滤函数   
  79. function get_int($number)   
  80. {   
  81.     return intval($number);   
  82. }   
  83. //字符串型过滤函数   
  84. function get_str($string)   
  85. {   
  86.     if (!get_magic_quotes_gpc()) {   
  87. return addslashes($string);   
  88.     }   
  89.     return $string;   
  90. }   
  91.   
  92.   
  93. 我们把以上代码放到一个公共的文件里,比如security.inc.php里面,每个文件里都include一下这个文件,那么就能够给任何一个程序进行提交的所有变量进行过滤了,就达到了我们一劳永逸的效果。    
]]>

原创文章,作者:键盘游走者,如若转载,请注明出处:http://www.708034.com/2007/12/php%e9%98%b2%e6%b3%a8%e5%85%a5%e5%ae%89%e5%85%a8%e4%bb%a3%e7%a0%81/

发表评论

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