background image

php 利用验证码防止恶意注册

常用的防止恶意注册就是利用验证码来实现了,在用户提交注册信息时我随机生成一个图

形验证码,这样只有人能识别了,当然简单的验证码机器是机以识别的,所以复杂点的好。

研究下

PHP 验证码,通过简单的数字验证码来实现,首先来写一个生成验证码的代码:

代码如下

<?php

//随机生成一个 4 位数的数字验证码

$num=”";     for($i=0;$i<4;$i++){     $num .= rand(0,9);     }

//4 位验证码也可以用 rand(1000,9999)直接生成

//将生成的验证码写入 session,备验证页面使用

Session_start();     $_SESSION["Checknum"] = $num;

//创建图片,定义颜色值     Header(“Content-type: image/PNG”);

srand((double)microtime()*1000000);

$im = imagecreate(60,20);

$black = ImageColorAllocate($im, 0,0,0);

$gray = ImageColorAllocate($im, 200,200,200);

imagefill($im,0,0,$gray);

//随机绘制两条虚线,起干扰作用

$style = array($black, $black, $black, $black, $black, $gray, $gray, $gray, $gray, $gray);

imagesetstyle($im, $style);

$y1=rand(0,20);     $y2=rand(0,20);     $y3=rand(0,20);     $y4=rand(0,20);

imageline($im, 0, $y1, 60, $y3, IMG_COLOR_STYLED);

imageline($im, 0, $y2, 60, $y4, IMG_COLOR_STYLED)

//在画布上随机生成大量黑点,起干扰作用;

for($i=0;$i<80;$i++)     {

imagesetpixel($im, rand(0,60), rand(0,20), $black);     }

//将四个数字随机显示在画布上,字符的水平间距和位置都按一定波动范围随机生成

$strx=rand(3,8);

for($i=0;$i<4;$i++){

$strpos=rand(1,6); 

     

 imagestring($im,5,$strx,$strpos,  substr($num,$i,1),  $black); 

$strx+=rand(8,12);

}

ImagePNG($im);     ImageDestroy($im);

?>

reg.php 页面我们写一个表单:(此处省去了其他的 HTML 代码)

代码如下

<tr>