一个实用的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的知识
Nov 17 PHP
ZF等常用php框架中存在的问题
Jan 10 PHP
PHP获取当前文件所在目录 getcwd()函数
May 13 PHP
使用PHP接收POST数据,解析json数据
Jun 28 PHP
PHP执行Curl时报错提示CURL ERROR: Recv failure: Connection reset by peer的解决方法
Jun 26 PHP
php上传文件问题汇总
Jan 30 PHP
php示例详解Constructor Prototype Pattern 原型模式
Oct 15 PHP
CodeIgniter扩展核心类实例详解
Jan 20 PHP
php同时使用session和cookie来保存用户登录信息的实现代码
May 13 PHP
thinkphp3.2实现跨控制器调用其他模块的方法
Mar 14 PHP
在Yii2特定页面如何禁用调试工具栏Debug Toolbar详解
Aug 07 PHP
使用vs code编辑调试php配置的方法
Jan 29 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
mysql_num_rows VS COUNT 效率问题分析
2011/04/23 PHP
Thinkphp模板标签if和eq的区别和比较实例分析
2015/07/01 PHP
PHP中模拟链表和链表的基本操作示例
2016/02/27 PHP
PHP迭代器接口Iterator用法分析
2017/12/28 PHP
thinkPHP3.2.3结合Laypage实现的分页功能示例
2018/05/28 PHP
PHP查找一列有序数组是否包含某值的方法
2020/02/07 PHP
JavaScript中通过闭包解决只能取得包含函数中任何变量最后一个值的问题
2010/08/12 Javascript
ExtJs中简单的登录界面制作方法
2010/08/19 Javascript
如何将一个String和多个String值进行比较思路分析
2013/04/22 Javascript
怎么选择Javascript框架(Javascript Framework)
2013/11/22 Javascript
js实现文字垂直滚动和鼠标悬停效果
2015/12/31 Javascript
JSON创建键值对(key是中文或者数字)方式详解
2017/08/24 Javascript
JS动态添加的div点击跳转到另一页面实现代码
2017/09/30 Javascript
vue判断input输入内容全是空格的方法
2018/03/02 Javascript
微信小程序自定义组件封装及父子间组件传值的方法
2018/08/28 Javascript
微信小程序实现复选框效果
2018/12/28 Javascript
如何在Vue中使localStorage具有响应式(思想实验)
2020/07/14 Javascript
vue实现验证用户名是否可用
2021/01/20 Vue.js
Python标准异常和异常处理详解
2015/02/02 Python
python清除指定目录内所有文件中script的方法
2015/06/30 Python
Python增量循环删除MySQL表数据的方法
2016/09/23 Python
详解Python 序列化Serialize 和 反序列化Deserialize
2017/08/20 Python
python抓取京东小米8手机配置信息
2018/11/13 Python
pygame实现俄罗斯方块游戏(基础篇2)
2019/10/29 Python
python属于跨平台语言码
2020/06/09 Python
Python如何操作docker redis过程解析
2020/08/10 Python
4款Python 类型检查工具,你选择哪个呢?
2020/10/30 Python
澳大利亚珍珠首饰购物网站:Vayo Pearls
2019/03/11 全球购物
工商管理专业学生的自我评价
2013/10/01 职场文书
北京奥运会主题口号
2014/06/13 职场文书
年度优秀员工获奖感言
2014/08/15 职场文书
银行党的群众路线教育实践活动对照检查材料
2014/09/25 职场文书
2014单位领导班子四风对照检查材料思想汇报
2014/09/25 职场文书
法院授权委托书格式
2014/09/28 职场文书
党的群众路线教育实践活动对照检查剖析材料
2014/10/09 职场文书
微信小程序APP的事件绑定以及传递参数时的冒泡和捕获
2022/04/19 Javascript