一个实用的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 相关文章推荐
介绍几个array库的新函数 php
Dec 29 PHP
php 防止单引号,双引号在接受页面转义
Jul 10 PHP
php 运行效率总结(提示程序速度)
Nov 26 PHP
PHP小技巧之JS和CSS优化工具Minify的使用方法
May 19 PHP
初识php MVC
Sep 10 PHP
PHP将字符分解为多个字符串的方法
Nov 22 PHP
WordPress导航菜单的滚动和淡入淡出效果的实现要点
Dec 14 PHP
Yii2基于Ajax自动获取表单数据的方法
Aug 10 PHP
php获取远程图片并下载保存到本地的方法分析
Oct 08 PHP
PHP微信企业号开发之回调模式开启与用法示例
Nov 25 PHP
ThinkPHP 5.x远程命令执行漏洞复现
Sep 23 PHP
laravel 获取某个查询的查询SQL语句方法
Oct 12 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
html中select语句读取mysql表中内容
2006/10/09 PHP
PHP+FFMPEG实现将视频自动转码成H264标准Mp4文件
2014/09/24 PHP
JScript中的undefined和&quot;undefined&quot;的区别
2007/03/08 Javascript
jquery中.add()的使用分析
2013/04/26 Javascript
Javascript异步编程模型Promise模式详细介绍
2014/05/08 Javascript
JQuery 给元素绑定click事件多次执行的解决方法
2014/09/09 Javascript
Jquery zTree 树控件异步加载操作
2016/02/25 Javascript
jquery实现点击弹出可放大居中及关闭的对话框(附demo源码下载)
2016/05/10 Javascript
深入剖析JavaScript:Object类型
2016/05/10 Javascript
javascript实现5秒倒计时并跳转功能
2019/06/20 Javascript
在React中写一个Animation组件为组件进入和离开加上动画/过度效果
2019/06/24 Javascript
js get和post请求实现代码解析
2020/02/06 Javascript
原生javascript制作贪吃蛇小游戏的方法分析
2020/02/26 Javascript
使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例
2014/01/19 Python
在Python中操作字符串之replace()方法的使用
2015/05/19 Python
详解python开发环境搭建
2016/12/16 Python
利用python操作SQLite数据库及文件操作详解
2017/09/22 Python
Python实现简单的文本相似度分析操作详解
2018/06/16 Python
Tensorflow加载预训练模型和保存模型的实例
2018/07/27 Python
Python Numpy库datetime类型的处理详解
2019/07/13 Python
Python基于OpenCV实现人脸检测并保存
2019/07/23 Python
Python队列RabbitMQ 使用方法实例记录
2019/08/05 Python
Boda Skins皮衣官网:奢侈皮夹克,全球配送
2016/12/15 全球购物
奥地利智能家居和智能生活网上商店:tink.at
2019/10/07 全球购物
力学专业毕业生自荐信
2013/11/17 职场文书
工作个人的自我评价
2014/01/14 职场文书
怎样拟定创业计划书
2014/05/01 职场文书
小学校长先进事迹材料
2014/05/13 职场文书
新学期开学演讲稿
2014/05/24 职场文书
销售团队口号大全
2014/06/06 职场文书
入党积极分子十八届四中全会思想汇报
2014/10/23 职场文书
优秀护士事迹材料
2014/12/25 职场文书
颐和园导游词400字
2015/01/30 职场文书
PHP使用QR Code生成二维码实例
2021/07/07 PHP
小程序与后端Java接口交互实现HelloWorld入门
2021/07/09 Java/Android
使用canvas对video视频某一刻截图功能
2021/09/25 HTML / CSS