验证码验证实例

  1 <?PHP
  2 /**
  3  * 验证码类
  4  */
  5  class VerificationCode
  6  {
  7      private $code;                //验证码内容
  8     private $codelen=4;            //验证码长度
  9     private $width=130;            //图片宽度
 10     private $height=50;            //图片高度
 11     private $img;                //图形资源句柄
 12     private $font="impact.ttf";//指定的字体
 13     private $fontsize=25;        //指定字体大小
 14     private $type=2;            //验证码内容模式
 15     private $dotNum=800;        //噪点数
 16     private $lineNum=20;        //干扰线数
 17 ////生成验证码内容
 18      private function randomCode()
 19     {
 20         $number="0123456789";
 21         $lowercaseLetters="qwertyuiopasdfghjklzxcvbnm";
 22         $capitalLetter="QWERTYUIOPASDFGHJKLZXCVBNM";
 23         switch ($this->type) //根据type设置验证码样本str
 24         {
 25             case 0://纯数字
 26                 $str=$number;
 27                 break;
 28             case 1://纯字母
 29                 $str=$lowercaseLetters.$capitalLetter;
 30                 break;
 31             case 2://数字+小写字母
 32                 $str=$number.$lowercaseLetters;
 33                 break;
 34             case 3://数字+字母
 35                 $str=$number.$lowercaseLetters.$capitalLetter;
 36                 break;
 37         }
 38         $code="";
 39         for ($i=0;$i<$this->codelen;$i++) 
 40             $code.=$str[rand(0,strlen($str)-1)];
 41         $this->code=$code;
 42     }
 43 ////获取随机颜色(较深)
 44     private function randomColor()
 45     {
 46         return imagecolorallocate($this->img,rand(0,200),rand(0,200),rand(0,200));
 47     }
 48 ////绘制画布
 49     private function createBg() 
 50     {
 51         /*resource imagecreatetruecolor(int $width,int $height)
 52         *新建一个大小为width*height的真彩色图像,返回图像标识符
 53         */
 54           $this->img=imagecreatetruecolor($this->width,$this->height);
 55           /*int imagecolorallocate(resource $image,int $red,int $green,int $blue)
 56           *返回一个标识符,代表了由给定的 RGB 成分组成的颜色。失败返回-1.
 57           *red,green 和 blue 分别是所需要的颜色的红,绿,蓝成分。
 58           这些参数是 0 到 255 的整数或者十六进制的 0x00 到 0xFF。
 59           */
 60           $bg=imagecolorallocate($this->img,rand(157,255),rand(157,255),rand(157,255));
 61           /*bool imagefill(resource $image,int $x,int $y,int $color)
 62           *在image图像的坐标x,y处(图像左上角为 0,0)用color颜色执行区域填充(即与x, y点颜色相同且相邻的点都会被填充)。
 63           */
 64           imagefill($this->img,0,0,$bg);
 65      }
 66  ////绘制噪点和干扰线noise
 67      private function createNoise() 
 68      {
 69          /*bool imagesetpixel(resource $image,int $x,int $y,int $color)
 70          *在 image 图像中用 color 颜色在 x,y 坐标(图像左上角为 0,0)上画一个点。
 71          */
 72          for ($i=0;$i<$this->dotNum;$i++)
 73             imagesetpixel($this->img,rand(0,$this->width),rand(0,$this->height),$this->randomColor());
 74         /*bool imageline(resource $image,int $x1,int $y1,int $x2,int $y2,int $color)
 75         *用 color 颜色在图像 image 中从坐标 x1,y1 到 x2,y2(图像左上角为 0, 0)画一条线段。
 76         */
 77         for ($i=0; $i <5 ; $i++)
 78             imageline($this->img,rand(0,$this->width),rand(0,$this->height),rand(0,$this->width),rand(0,$this->height),$this->randomColor());
 79      }
 80  ////绘制验证码
 81      private function createFont() 
 82      {
 83          /*array imagettftext(resource $image,float $size,float $angle,int $x,int $y,int $color,string $fontfile,string $text)
 84          *使用 TrueType 字体将 指定的text写入图像image。 
 85          *image,由图象创建函数(例如 imagecreatetruecolor() )返回的图象资源。
 86          *size,字体的尺寸。
 87          *angle,角度制表示的角度,0 度为从左向右读的文本。更高数值表示逆时针旋转。例如 90 度表示从下向上读的文本。 
 88          *x和y,表示的坐标定义了第一个字符的基本点(大概是字符的左下角)。
 89          *color,颜色索引。
 90          *fontfile,想要使用的 TrueType 字体的路径。
 91          *text,UTF-8 编码的文本字符串。 
 92          */
 93          for ($i=0;$i<$this->codelen;$i++) 
 94          {
 95              $randomFZ=rand($this->fontsize,$this->fontsize+10);
 96              $randomAngle=rand(-40,40);
 97              $x=20+$this->fontsize*$i;
 98              $y=40;
 99              $fontcolor=imagecolorallocate($this->img,rand(0,156),rand(0,156),rand(0,156));
100             imagettftext($this->img,$randomFZ,$randomAngle,$x,$y,$fontcolor,$this->font,$this->code[$i]);
101          }
102      }
103  ////输出图像并释放内存
104      private function outPut()
105      {
106          /*输出png格式图像*/
107          header("Content-Type:image/png");
108          /*bool imagepng(resource $image[,string $filename])
109          *将 GD 图像流(image)以 PNG 格式输出到标准输出(通常为浏览器),或者如果用 filename 给出了文件名则将其输出到该文件。
110          */
111         imagepng($this->img);
112         /*bool imagedestroy(resource $image)
113         *释放与 image 关联的内存。
114         */
115         imagedestroy($this->img);
116      }
117  ////生成完整二维码
118      public  function getvc()
119      {
120          $this->createBg();//生成画布
121           $this->randomCode();//生成验证码
122           $this->createFont();//绘制验证码
123           $this->createNoise();//绘制噪点和干扰线
124           $this->outPut();//输出图像并释放内存
125      }
126  ////获取验证码答案
127      public  function getCode()
128      {
129          return $this->code;
130      }
131  } 
132 ?>
验证码封装类VerificationCode.class.php
 1 <?PHP 
 2     /*
 3     *创建VerificationCode的实例对象,生成验证码图片并将正确答案存入session
 4     */
 5     session_start();
 6     require_once "VerificationCode.class.php";
 7     $verificationCode=new VerificationCode();
 8     $verificationCode->getvc();
 9     $_SESSION["VerificationCode"] = $verificationCode->getCode();
10 ?>
captcha.php
 1 <?PHP 
 2     /*获取验证码答案*/
 3     session_start();
 4     if (isset($_SESSION['VerificationCode'])) {
 5         $VerificationCode=$_SESSION['VerificationCode'];
 6     } else {
 7         die("获取验证码答案失败!!");
 8     }
 9 ?>
10 <html>
11     <head>
12         <title>图片验证实例</title>
13         <meta http-equiv = "content-type" content="text/html; charset = utf-8 " >
14     </head> 
15     <body> 
16         <form action="" method="post">
17             <p>
18                 <!--验证码-->
19                 <img  title="点击更换" src="captcha.php" align="absbottom" οnclick="this.src='captcha.php?'+Math.random();"></img>
20                 <input type="text" name="validate" value="" size=10> 
21                 <DIV class="error"><?PHP 
22                     $validate="";
23                     if(isset($_POST["validate"]))
24                     {
25                         $validate=$_POST["validate"];
26                         echo "您刚才输入的是:".$_POST["validate"]."<br>";
27                         echo "正&nbsp确&nbsp答&nbsp案&nbsp是:".$VerificationCode."<br>";
28                         if($validate!=$VerificationCode)
29                             echo "<font color=red>输入有误</font>"; 
30                         else
31                             echo "<font color=green>通过验证</font>"; 
32                     } 
33                 ?></DIV>
34             </p>
35             <p><input type="submit" value="确定"></p>
36         </form>
37     </body>
38 </html>
mainview.php

 

转载于:https://www.cnblogs.com/maguariji/p/7290085.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java生成和验证验证码的示例: ``` import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CaptchaServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final int WIDTH = 120; private static final int HEIGHT = 40; private static final int LENGTH = 4; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, WIDTH, HEIGHT); g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(WIDTH); int y = random.nextInt(HEIGHT); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } StringBuffer sRand = new StringBuffer(); for (int i = 0; i < LENGTH; i++) { String rand = String.valueOf(random.nextInt(10)); sRand.append(rand); g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 13 * i + 6, 16); } request.getSession().setAttribute("captcha", sRand.toString()); g.dispose(); ImageIO.write(image, "JPEG", out); out.close(); } private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } } ``` 这个Servlet会在请求时生成一个验证码并将其写入一个JPEG图像中,然后将该图像发送回浏览器。要验证用户输入的验证码,只需检查该值是否与上一个请求中存储在会话中的验证码相同即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值