Thinkphp通过标签扩展实现验证码

来源:互联网 发布:可牛淘宝图片助手 编辑:程序博客网 时间:2024/06/07 13:59
用Thinkphp实现验证码很简单,但如果一个项目有很多地方要用到它呢,这时通过标签拓展来实现验证码就成了首选。
下面小编通过一个栗子,来让大家学会如何去实现~
虽然小编用的是thinkphp3.2.1版本展示的,不过不用担心,其他版本的thinkphp目录结构稍有变化,只要读懂这个栗子,举一反三类推即可。

1、首先在Application/Home/Controller中创建  PublicController.class.php
代码如下:
 //通过code方法来显示验证码,引入ORG.Util.Image类库和ORG.Util.String类库。 <?php     class PublicController extends Controller {        public function code(){           $w=isset($_GET['w'])?$_GET['w']:30;           $h=isset($_GET['h'])?$_GET['h']:30;           import('ORG.Util.Image');           Image::buildImageVerify(2,1,'png',$w,$h,'code');      //Image类的buildImageVerify方法用于生成验证码        }    }  ?>
2、其次 在ThinkPHP\Library\Think\Template\TagLib 创建TagLibMessage.class.php
代码如下:
<?php   Class TagLibMessage extends TagLib{     //必须继承于TagLib        protected $tags   =  array(              // 定义code 标签             'code'=>array('attr'=>'width,height','close'=>0),  //attr:标签支持的属性列表,用逗号隔开        );       //每个标签的解析方法在定义的时候需要添加“_”前缀,可以传入两个参数,属性字符串和内容字符串(针对非闭合标签)。必须通过return 返回标签的字符串解析输出       public function _code($attr)   {              $tag     =  $this->parseXmlAttr($attr,'code');//表示分析input标签的标签定义,并返回input的所有标签属性              $width   =  $tag['width'];              $height  =  $tag['height'];              $str = "<img src='__APP__/Public/code?w={$width}&h={$height}' onclick='this.src=this.src+\"?\"+Math.random()'/>";              return $str;         }    }?>
3、最后是html部分:
(1)在涉及到验证码的Html页面,将
<taglib name='Message' />    //Message 与TagLibMessage保持一致
这段代码插入到该页面html代码的第一行(必须在第一行)
(2)之后在适当位置加入以下html代码即可     
  验证码:<input type='text' name='code'/>          <Message:code  width='30' height='30'/>       //Message下的code标签  <br/>
原创粉丝点击