php图片验证码技术

    技术2022-05-11  106

    php图片验证码技术现在越来越多的网站用到了验证码技术,而且是随即生成图片,这样的技术在某种程度上可以阻止一定使用不法手段的攻击,盗取账号等等的不法分子!~ 好了,还是开是讲讲php中这种技术的实现吧! 其实,在php中,这种技术实现很简单,由于我在自己的网站中就遇到不法分子利用软件在“BLOG留言”栏目发布大量垃圾信息,所以想到用IP限制访问和一个验证码技术,就研究了一下,其思路大致是这样的,随即生成一个随机数,大多为4位数字和字母,或者是数字和字母的组合,生成以后,用GD库的支持生成一张根据随机数来确定的图片,把随机数写入到session中,传递到要验证的页面,生成的图片显示给登陆着,并要求登陆者输入该随机数内容,提交到验证页面,验证session的内容和提交的内容是否一致,这就是大致的思路! 代码大致如下: <? /* $width :图片宽 $height : 图片高 $space : 字符间距(中心间距) $size : 字符大小(1-5) $line_num : 干扰线条数 $length : 字符串长度 $sname :SESSION名称(供下一步验证之用) */ session_start(); creat_code(45,15,10,3,5,5,"code_str"); function creat_code($width, $height, $space, $size, $line_num, $length, $sname="") {  $left = 3; // 字符左间距  $top = 1;// 右间距  $move = 3; //上下错位幅度  // 生成字符串  srand((double)microtime()*1000000);  $possible = "0123456789"."ABCDEFGHIJKLMNOPQRSTUVWXYZ";  $authstr = "";  while(strlen($authstr) < $length) {  $authstr .= substr($possible, rand(0,strlen($possible)), 1);  }   // 设置SESSION  if ($sname != "") {  $_SESSION[$sname] = $authstr;  }  // 初始化图片  $image = imagecreate($width,$height);   // 设定颜色  $black = ImageColorAllocate($image, 0, 0, 0);  $white = ImageColorAllocate($image, 255, 255, 255);  $gray = ImageColorAllocate($image, 80, 80, 80);  $silver = ImageColorAllocate($image, 240, 240, 240);  $msilver = ImageColorAllocate($image, 220, 220, 220);  $bg_white = ImageColorAllocate($image, 255, 255, 255);  // 生成背景  imagefill($image,0,0,$gray);  // 画出字符  for ($i = 0; $i < strlen($authstr); $i++) {  $y = ($i%2)*$move + $top;  imagestring($image, $size, $space*$i+$left, $y, substr($authstr,$i,1), $white);  }   // 画出横向干扰线  if ($i > 0) {  $line_space = ceil($height/($line_num+2));  for ($i = 1; $i <= $line_num; $i++) {  $y = $line_space*$i;  imageline($image, 0, $y, $width, $y, $silver);  }  }  // 输出图象  Header("Content-type: image/PNG");  ImagePNG($image);  ImageDestroy($image); } ?> 以上是生成了一个随即的数字和字母混合的4位验证码图片,我们只需要在要调用的地方调用这个图片即可: <img src="yanzheng.php" width="50" height="18" border=0 alt=""> 其中yanzheng.php即上面的程序的名称! 也可以使用纯数字的验证码技术,方法一样! /纯数字的/// $num = mt_rand(1000,9999); $im = imagecreate(50,18); $black = ImageColorAllocate($im,0,0,0); $white = ImageColorAllocate($im,255,255,255); $gray = ImageColorAllocate($im,200,200,200); imagefill($im,68,30,$gray); imagestring($im, 5, 8, 2, $num, $white); for($i=0;$i<100;$i++) //加入干扰象素 { imagesetpixel($im, rand()p , rand()0 , $gray);} ImagePNG($im); ImageDestroy($im); 至于传递等等,由你自己实现吧!~

    最新回复(0)