一个实用的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中的时间处理
Oct 09 PHP
PHP strstr 函数判断字符串是否否存在的实例代码
Sep 28 PHP
php使用cookie实现记住登录状态
Apr 27 PHP
修改WordPress中文章编辑器的样式的方法详解
Dec 15 PHP
PHP采用超长(超大)数字运算防止数字以科学计数法显示的方法
Apr 01 PHP
制作个性化的WordPress登陆界面的实例教程
May 21 PHP
浅谈Coreseek、Sphinx-for-chinaese、Sphinx+Scws的区别
Dec 15 PHP
PHP微信PC二维码登陆的实现思路
Jul 13 PHP
ThinkPHP框架实现导出excel数据的方法示例【基于PHPExcel】
May 12 PHP
在Laravel中使用DataTables插件的方法
May 29 PHP
laravel 解决后端无法获取到前端Post过来的值问题
Oct 22 PHP
php和js实现根据子网掩码和ip计算子网功能示例
Nov 09 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中去除所有js,html,css代码
2010/10/12 PHP
PHP正确配置mysql(apache环境)
2011/08/28 PHP
php中通过正则表达式下载内容中的远程图片的函数代码
2012/01/10 PHP
php利用嵌套数组拼接与解析json的方法
2017/02/07 PHP
PHP设计模式之装饰器模式定义与用法详解
2018/04/02 PHP
PHP针对redis常用操作实例详解
2019/08/17 PHP
SWFObject Flash js调用类
2008/07/08 Javascript
js调试工具 Javascript Debug Toolkit 2.0.0版本发布
2008/12/02 Javascript
动态刷新 dorado树的js代码
2009/06/12 Javascript
jquery 框架使用教程 AJAX篇
2009/10/11 Javascript
JavaScript创建一个欢迎cookie弹出窗实现代码
2013/03/15 Javascript
js字符串日期yyyy-MM-dd转化为date示例代码
2014/03/06 Javascript
JavaScript简单表格编辑功能实现方法
2015/04/16 Javascript
FullCalendar日历插件应用之数据展现(一)
2015/12/23 Javascript
深入理解jQuery3.0的domManip函数
2016/09/01 Javascript
Bootstrap 3.x打印预览背景色与文字显示异常的解决
2016/11/06 Javascript
javascript 利用arguments实现可变长参数
2016/11/21 Javascript
通过jsonp获取json数据实现AJAX跨域请求
2017/01/22 Javascript
Angular.Js中过滤器filter与自定义过滤器filter实例详解
2017/05/08 Javascript
深入浅析JavaScript中的RegExp对象
2017/09/18 Javascript
纯js代码生成可搜索选择下拉列表的实例
2018/01/11 Javascript
详解vue添加删除元素的方法
2018/06/30 Javascript
深入浅析golang zap 日志库使用(含文件切割、分级别存储和全局使用等)
2020/02/19 Javascript
微信小程序国际化探索实现(附源码地址)
2020/05/20 Javascript
[01:02:04]EG vs Liquid 2019国际邀请赛淘汰赛 败者组 BO3 第一场 8.23
2019/09/05 DOTA
web.py获取上传文件名的正确方法
2014/08/26 Python
python正常时间和unix时间戳相互转换的方法
2015/04/23 Python
Python制作简单的网页爬虫
2015/11/22 Python
django使用LDAP验证的方法示例
2018/12/10 Python
Python根据欧拉角求旋转矩阵的实例
2019/01/28 Python
初二生物教学反思
2014/02/03 职场文书
课堂教学改革实施方案
2014/03/17 职场文书
学生党员检讨书范文
2014/12/27 职场文书
修辞手法有哪些?
2019/08/29 职场文书
Python实战之用tkinter库做一个鼠标模拟点击器
2021/04/27 Python
Python中json.dumps()函数的使用解析
2021/05/17 Python