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

一分钟学会使用PHP生成网页验证码

2013年08月09日 ⁄ 综合 ⁄ 共 1537字 ⁄ 字号 评论关闭

    现在Web页面上的表单一般都会内嵌一条验证码输入,以防止服务器被恶意DoS攻击或者不法之徒利用机器程序自动贴牛皮癣广告。

在PHP里的简单实现方法如下:

1. 首先在表单页面展现之前,生成一副图片,并添加上一些干扰像素或线段(防止OCR程序自动识别)

再由PHP程序自动生成随机的待验证的一串数字和字母组合的字符, 调用imagettftext()函数画到图片中,

并把这串字符保存到Session级变量中。

以下为生成验证码的文件authcode.php (需要php gd库的支持,否则无法正常显示验证码图片)

<?php
 session_start();
 header("Content-type:image/PNG");
 
 srand((double)microtime() * 1000000);
 $imagewidth = 60;
 $imageheight = 20;
 $authimage = imagecreate($imagewidth, $imageheight);
 $black = ImageColorAllocate($authimage, 0, 0, 0);
 $white = ImageColorAllocate($authimage, 255, 255, 255);
 $red = ImageColorAllocate($authimage, 255, 0, 0);
 $gray = ImageColorAllocate($authimage, 200, 200, 200);
 //背景颜色为灰色
 imagefill($authimage, 0, 0, $gray);

 //随机的生成一些干扰像素
 for($i = 0; $i < 400; $i++)
 {
    $randcolor = ImageColorallocate($authimage, rand(10, 255), rand(10, 255), rand(10, 255));
    imagesetpixel($authimage, rand()%$imagewidth, rand()%$imageheight, $randcolor); 
 }
 
 //随机的画几条线段
 for($i = 0; $i < 6; $i++)
 {
  imageline($authimage, rand()%$imagewidth, rand()%$imageheight,
   rand()%$imagewidth, rand()%$imageheight, $black);
 }
 
 //生成验证串
 $array = "0123456789abcdefghijklmnopqrstuvwxyz";
 for($i = 0; $i < 4; $i++)
 {
  $authcode .=substr($array, rand(0, 35), 1);
 }
 imagettftext($authimage, 20, 0, 0, $imageheight, $red, 'arial.ttf', $authcode);

 ImagePNG($authimage);
 ImageDestroy($authimage);
 $_SESSION['authcode'] = $authcode;
?>

2. 在form表单中添加显示验证码图片

验证码:<input type="text" name="authcode" id="textfield"/>
 <img src = "authcode.php" /><br />

3. 当用户提交输入后,就可以验证所输入的验证码与服务器端保存的验证码是否一致。

  if(strcmp($_SESSION['authcode'], $_POST['authcode']))
  {
   echo "<script>alert('验证码输入错误!');</script>";
  }

 

抱歉!评论已关闭.