一个实用的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 pack与unpack 摸板字符字符含义
Oct 29 PHP
php session和cookie使用说明
Apr 07 PHP
PHP中运用jQuery的Ajax跨域调用实现代码
Feb 21 PHP
php跨域cookie共享使用方法
Feb 20 PHP
php实现文件下载代码分享
Aug 19 PHP
PHP 魔术变量和魔术函数详解
Feb 25 PHP
PHP设置进度条的方法
Jul 08 PHP
php制作基于xml的RSS订阅源功能示例
Feb 08 PHP
thinkPHP中钩子的使用方法实例分析
Nov 16 PHP
PHP封装的XML简单操作类完整实例
Nov 13 PHP
浅谈laravel 5.6 安装 windows上使用composer的安装过程
Oct 18 PHP
XAMPP升级PHP版本实现步骤解析
Sep 04 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
自己动手,丰衣足食 - 短波框形天线制作
2021/03/01 无线电
处理php自动反斜杠的函数代码
2010/01/05 PHP
PHP冒泡排序算法代码详细解读
2011/07/17 PHP
简单实现PHP留言板功能
2016/12/21 PHP
php与c 实现按行读取文件实例代码
2017/01/03 PHP
Google的跟踪代码 动态加载js代码方法应用
2012/11/12 Javascript
jQuery之选项卡的简单实现
2014/02/28 Javascript
详解Javascript 装载和执行
2014/11/17 Javascript
jQuery实现的感应鼠标悬停图片色彩渐显效果
2015/03/03 Javascript
使用javaScript动态加载Js文件和Css文件
2015/10/24 Javascript
JS使用post提交的两种方式
2015/12/03 Javascript
基于javascript实现全国省市二级联动下拉选择菜单
2016/01/28 Javascript
JavaScript中的闭包
2016/02/24 Javascript
AngularJS  自定义指令详解及实例代码
2016/09/14 Javascript
Angular.js中$apply()和$digest()的深入理解
2016/10/13 Javascript
Ajax与服务器(JSON)通信实例代码
2016/11/05 Javascript
BootStrap Table后台分页时前台删除最后一页所有数据refresh刷新后无数据问题
2016/12/28 Javascript
vue监听滚动事件实现滚动监听
2017/04/11 Javascript
jQuery实现多张图片上传预览(不经过后端处理)
2017/04/29 jQuery
node创建Vue项目步骤详解
2020/03/06 Javascript
JS严格模式原理与用法实例分析
2020/04/27 Javascript
vue样式穿透 ::v-deep的具体使用
2020/06/04 Javascript
[01:14]英雄,所敬略同——2018完美盛典宣传视频
2018/12/05 DOTA
[46:55]LGD vs Liquid 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/19 DOTA
pycharm远程开发项目的实现步骤
2019/01/20 Python
Appium+python自动化之连接模拟器并启动淘宝APP(超详解)
2019/06/17 Python
Pycharm 2019 破解激活方法图文详解
2019/10/11 Python
Python Tensor FLow简单使用方法实例详解
2020/01/14 Python
css3实现六边形边框的实例代码
2019/05/24 HTML / CSS
解决html5中video标签无法播放mp4问题的办法
2017/05/07 HTML / CSS
Argos官网:英国家喻户晓的百货零售连锁商
2017/04/03 全球购物
应届本科生推荐信范文
2013/12/25 职场文书
学期个人工作总结
2015/02/13 职场文书
2015年小学教师培训工作总结
2015/07/21 职场文书
聊聊pytorch测试的时候为何要加上model.eval()
2021/05/23 Python
在SQL Server中使用 Try Catch 处理异常的示例详解
2022/07/15 SQL Server