一个实用的php验证码类


Posted in PHP onJuly 06, 2017

万能php验证码类,供大家参考,具体内容如下

code.php是验证码类,类的名称最好和文件名的名称一样,这样有利于我们的查看。

code.php

<?php
header('Content-type:text/html;charset=utf8');
class Code{
  // 验证码个数$number
  protected $number;
  // 验证码类型$codeType
  protected $codeType;
  // 验证码图像宽度$width
  protected $width;
  // 验证码$height
  protected $height;
  // 验证码字符串$code
  protected $code;
  // 图像资源$image
  protected $image;
  
  public function __construct($number=4,$codeType=0,$height=50,$width=100){
    //初始化自己的成员属性
    $this->number=$number;
    $this->codeType=$codeType;
    $this->width = $width;
    $this->height= $height;
    
    //生成验证码函数
    $this->code = $this ->createCode();
    
  }
  public function __get($name){
    if ($name == 'code'){
      return $this->code;
    }
    return false;
  }
  /*获取验证码*/
  public function getCode() {
    return $this->code;
  }
  /*图像资源销毁*/
  public function __destruct(){
    imagedestroy($this->image);
  }
  protected function createCode(){
    //通过你的验证码类型生成验证码
    switch ($this->codeType){
      case 0: //纯数字
        $code = $this->getNumberCode();
        break;
      case 1: //纯字母的
        $code = $this->getCharCode();
        break;
      case 2: //数字和字母混合
        $code = $this->getNumCharCode();
        break;
      default:
        die('不支持此类验证码类型');
    }
    return $code;
  }
  protected function getNumberCode(){
    $str = join('', range(0, 9));
    return substr(str_shuffle($str),0, $this->number);
  }
  protected function getCharCode(){
    $str = join('', range('a', 'z'));
    $str = $str.strtoupper($str);
    return substr(str_shuffle($str),0,$this->number);
  }
  protected function getNumCharCode(){
    $numstr = join('',range(0, 9));
    $str =join('', range('a', 'z'));
    $str =$numstr.$str.strtoupper($str);
    return substr(str_shuffle($str), 0,$this->number);
  }
  protected function createImage(){
    $this->image = imagecreatetruecolor($this->width, 
        $this->height);
  }
  protected function fillBack(){
    imagefill($this->image, 0, 0, $this->lightColor());
  }
  /*浅色*/
  protected function lightColor(){
    return imagecolorallocate($this->image, mt_rand(133,255), mt_rand(133,255), mt_rand(133,255));
  }
  /*深色*/
  protected function darkColor(){
    return imagecolorallocate($this->image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
  }
  protected function drawChar(){
    $width = ceil($this->width / $this->number);
    for ($i=0; $i< $this->number;$i++){
      $x = mt_rand($i*$width+5, ($i+1)*$width-10);
      $y = mt_rand(0, $this->height -15);
      imagechar($this->image, 5, $x, $y, $this->code[$i], $this->darkColor());
    }
  }
  protected function drawLine(){
    for ($i=0;$i<5;$i++) {
      imageline($this->image,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$this->darkColor());
    }
  }
  protected function drawDisturb(){
    for ($i=0;$i<150;$i++){
      $x=mt_rand(0, $this->width);
      $y=mt_rand(0, $this->height);
      imagesetpixel($this->image, $x, $y, $this->lightColor());
    }
  }
  protected function show(){
    header('Content-Type:image/png');
    imagepng($this->image);
  }
  public function outImage(){
//     创建画布
    $this->createImage();
//     填充背景色
    $this->fillBack();
//     将验证码字符串花到画布上
    $this->drawChar();
//     添加干扰元素
    $this->drawDisturb();
//     添加线条
    $this->drawLine();
//     输出并显示
    $this->show();
  }
}

test.php是new一个新的验证码,并把它保存到session中,为我们验证码的验证起到保存和存储的作用。

test.php

<?php
//开启session
session_start();
require_once 'code.php';

$code= new Code(4,1,50,100);
$_SESSION['code']= $code->getCode();
$code->outImage();

login.php就是最后的验证。

login.php

<?php 
    //开启Session 
    session_start(); 
    //判断是否提交 
    if(isset($_POST['dosubmit'])){ 
      //获取session中的验证码并转为小写 
      $sessionCode=strtolower($_SESSION['code']); 
      //获取输入的验证码 
      $code=strtolower($_POST['code']); 
      //判断是否相等 
      if($sessionCode==$code){ 
        echo "<script type='text/javascript'>alert('验证码正确!');</script>"; 
      }else{ 
        echo "<script type='text/javascript'>alert('验证码错误!');</script>"; 
      } 
    } 
  ?> 
  <!DOCTYPE html> 
  <html> 
    <head> 
      <title></title> 
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> 
      <style type="text/css"> 
        *{margin:0px;padding:0px;} 
        ul{ 
          width:400px; 
          list-style:none; 
          margin:50px auto; 
        } 
         
        li{ 
          padding:12px; 
          position:relative; 
        } 
         
        label{ 
          width:80px; 
          display:inline-block; 
          float:left; 
          line-height:30px; 
        } 
         
        input[type='text'],input[type='password']{ 
          height:30px; 
        } 
         
        img{ 
          margin-left:10px; 
        } 
         
        input[type="submit"]{ 
          margin-left:80px; 
          padding:5px 10px; 
        } 
      </style> 
    </head> 
    <body> 
      <form action="login.php" method="post"> 
        <ul> 
          <li> 
            <label>用户名:</label> 
            <input type="text" name="username"/> 
          </li> 
          <li> 
            <label>密码:</label> 
            <input type="password" name="password"/> 
          </li> 
          <li> 
            <label>验证码:</label> 
            <input type="text" name="code" size="4" style="float:left"/> 
            <img src="test.php" onclick="this.src='test.php?Math.random()'"/> 
          </li> 
          <li> 
            <input type="submit" value="登录" name="dosubmit"/> 
          </li> 
        </ul> 
      </form> 
    </body> 
  </html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
php防止伪造的数据从URL提交方法
Jun 27 PHP
PHP反射使用实例和PHP反射API的中文说明
Jul 02 PHP
php在linux下检测mysql同步状态的方法
Jan 15 PHP
php-redis中的sort排序函数总结
Jul 08 PHP
ThinkPHP数据操作方法总结
Sep 28 PHP
详解WordPress中过滤链接与过滤SQL语句的方法
Dec 18 PHP
Android App中DrawerLayout抽屉效果的菜单编写实例
Mar 21 PHP
php  PATH_SEPARATOR判断当前服务器系统类型实例
Oct 28 PHP
PHP数字前补0的自带函数sprintf 和number_format的用法(详解)
Feb 06 PHP
PHP Laravel 上传图片、文件等类封装
Aug 16 PHP
Laravel框架实现利用监听器进行sql语句记录功能
Jun 06 PHP
PHP实现的DES加密解密类定义与用法示例
Nov 02 PHP
万能的php分页类
Jul 06 #PHP
PHP 实现从数据库导出到.csv文件方法
Jul 06 #PHP
php文件上传类的分享
Jul 06 #PHP
PHP图片水印类的封装
Jul 06 #PHP
php生出随机字符串
Jul 06 #PHP
PHP实现的分页类定义与用法示例
Jul 05 #PHP
PHP实现的文件上传类与用法详解
Jul 05 #PHP
You might like
PHP中图片等比缩放的实例
2013/03/24 PHP
PHP多进程编程实例
2014/10/15 PHP
PHP生成唯一订单号的方法汇总
2015/04/16 PHP
php提取身份证号码中的生日日期以及验证是否为成年人的函数
2015/09/29 PHP
多个iframe自动调整大小的问题
2006/09/18 Javascript
很棒的学习jQuery的12个网站推荐
2011/04/28 Javascript
JavaScript的21条基本知识点
2014/03/04 Javascript
Jqgrid之强大的表格插件应用
2015/12/02 Javascript
延时加载JavaScript代码提高速度
2015/12/27 Javascript
jQuery页面刷新(局部、全部)问题分析
2016/01/09 Javascript
checkbox 选中一个另一个checkbox也会选中的实现代码
2016/07/09 Javascript
EasyUI折叠表格层次显示detailview详解及实例
2016/12/28 Javascript
vue.js利用defineProperty实现数据的双向绑定
2017/04/28 Javascript
面包屑导航详解
2017/12/07 Javascript
微信小程序实现带缩略图轮播效果
2018/11/04 Javascript
详解如何为你的angular app构建一个第三方库
2018/12/07 Javascript
[02:15]2015国际邀请赛选手档案IG.Ferrari 430
2015/07/30 DOTA
[00:12]DAC2018 Miracle-站上中单舞台,他能否再写奇迹?
2018/04/06 DOTA
wxpython 学习笔记 第一天
2009/03/16 Python
Python中os和shutil模块实用方法集锦
2014/05/13 Python
python检查URL是否正常访问的小技巧
2017/02/25 Python
详解PANDAS 数据合并与重塑(join/merge篇)
2019/07/09 Python
python scipy卷积运算的实现方法
2019/09/16 Python
python3实现elasticsearch批量更新数据
2019/12/03 Python
Pytorch Tensor基本数学运算详解
2019/12/30 Python
解决springboot yml配置 logging.level 报错问题
2020/02/21 Python
pyMySQL SQL语句传参问题,单个参数或多个参数说明
2020/06/06 Python
从Pytorch模型pth文件中读取参数成numpy矩阵的操作
2021/03/04 Python
我能否用void** 指针作为参数, 使函数按引用接受一般指针
2013/02/16 面试题
建筑设计专业求职自我评价
2014/03/02 职场文书
元旦晚会感言
2014/03/12 职场文书
大班上学期幼儿评语
2014/04/30 职场文书
遵纪守法演讲稿
2014/05/23 职场文书
父亲节寄语大全
2015/02/27 职场文书
幼儿园开学温馨提示
2015/07/15 职场文书
《分一些蚊子进来》读后感3篇
2020/01/09 职场文书