现在的位置: 首页 > 综合 > 正文

php中安全补充

2011年03月09日 ⁄ 综合 ⁄ 共 2468字 ⁄ 字号 评论关闭

1 设置脚本可以访问的目录,一定限度上限制了PHP木马,比如
    open_basedir=d:/usr/www

   一般设置将php能打开的文件设置在指定的目录树中.

2 设置禁用的函数

    disable_functions,在php.ini的safe_mode=off下,可以用这个。

在php.ini中,比如
disable_functions = phpinfo,get_cfg_var
又或者
disable_functions= passthru,exec,shell_exec,system,fopen,mkdir,rmdir,chmod,unlink,dir ,fopen,fread,fclose,fwrite,file_exists ,closedir,is_dir,readdir.opendir ,fileperms.copy,unlink,delfile

但有的文件函数就用不了拉.

 

3 打开magic_quotes_gpc

  默认是关闭的,打开的话,会自动转义.

如果关闭的话,就用addslashes()咯

 

4 网上很多防止注入的程序,比如
 

<?php
/*
PHP整站防注程序,需要在公共文件中reqire_once本文件
by 风尘浪子 QQ:156544632 http://156544632.cn
*/
// 判断 magic_quotes_gpc 状态
if (@get_magic_quotes_gpc()) {
    $_GET = sec($_GET);
    $_POST = sec($_POST);
    $_COOKIE = sec($_COOKIE);
    $_FILES = sec($_FILES);
}
$_SERVER = sec($_SERVER);

function sec(&$array) {
//如果是数组
 if (is_array($array)) {
//遍历数组
  foreach ($array as $k => $v) {
//递归调用
   $array[$k] = sec($v);
  }
 } else if (is_string($array)) {
//stripslashes函数来处理
  $array = addslashes($array);
 }else if (is_numeric($array)) {
//intval函数来处理
  $array = intval($array);
 }
 return $array;
}

function num_check($id) {
  if (!$id) {die('参数不能为空!'); }    // 是否为空判断
  elseif (inject_check($id)) { die('非法参数!'); }    // 注射判断
  elseif (!is_numeric($id)) { die('非法参数!'); }    // 数字判断
  $id = intval($id);    // 整型化
  return  $id;
}

function str_check( $str) {
  $str= htmlspecialchars($str);  //转换Html
  return $str;
}
function search_check( $str) {
  $str = str_replace("_", "\_", $str);    // 把 '_'过滤掉
  $str = str_replace("%", "\%", $str);    // 把 '%'过滤掉
  $str= htmlspecialchars($str);  //转换Html
  return $str;
}

function post_check( $str,$min,$max) {
if(isset($min)&&strlen($str) < $min){
 die("最少$min字节");
}elseif(isset($max)&&strlen($str) >$max){
 die("最多$max字节");
}
  return stripslashes_array($str);
}

function inject_check($sql_str) {
  return eregi('select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str);    // 进行过滤
}


?>

 

 

4 防止远程文件包含
  关闭allow_url_fopen

5 防止把表单保存下来再提交
  if($_SERVER['REQUEST_METHOD'] == 'POST' && (empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) !== preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST']))) {
 die('来路不正确');
}

 

6 对比如用户发表评论后的东西回显到屏幕时,注意把html过滤掉
   // 清除HTML代码
function html_clean($content) {
 $content = htmlspecialchars($content);
 $content = str_replace("\n", "<br />", $content);
 $content = str_replace("  ", "&nbsp;&nbsp;", $content);
 $content = str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", $content);
 $content = preg_replace("/\[quote=(.*?)\]\s*(.+?)\s*\[\/quote\]/is", "<div style=\"font-weight: bold\">引用 \\1 的评论:</div><div class=\"quote\">\\2</div>", $content);
 return $content;
}
   

抱歉!评论已关闭.