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

    现在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>";
  }

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值