---
title: "thinkphp验证码的使用"
author: "crazymud"
date: "2009-08-17T22:20:05Z"
tags: []
categories: ["编程语言"]
slug: "thinkphp"
draft: false
lastmod: "2009-08-17T22:20:05Z"
id: 451667
url: "https://crazymud.iteye.com/blog/451667"
---

在thinkphp中使用验证码很容易，只要调用thinkphp现有的方法就可以。当然，php的GD库肯定是要开的。

首先，在写Action文件，如：IndexAction.class.php.

```
<?php
class IndexAction extends Action{
	//显示验证码
	public function verifyTest() {
	  $this->display();
	}
	
	//检验验证码是否正确
	public function verifyCheck() {
	  //防止页面乱码
          header('Content-type:text/html;charset=utf-8');
	  
	  if (md5($_POST['verifyTest']) != Session::get('verify')) {
	    echo '验证码错误';
	  }
	  else {
	    echo '验证码正确';
          }
	}
	
	// 生成验证码
	public function verify() {
            import("ORG.Util.Image");
            Image::buildImageVerify();
	}
}
?>
```

 在对应的模板文件：Tpl\\default\\index目录下新建文件verifyTest.html，内容如下：

```
<script type='text/javascript'>
//重载验证码
function freshVerify() {
  document.getElementById('verifyImg').src='__URL__/verify/'+Math.random();
}
</script>
<form method='post' action='__URL__/verifyCheck'>
<input type='text' name='verifyTest'>
<img style='cursor:pointer' title='刷新验证码' src='__URL__/verify' id='verifyImg' onClick='freshVerify()'/>
<button type='submit'>确定</button>
</form>
```

 view如下：

![](/upload/picture/pic/42593/513283d1-544b-3148-8ec0-718e050847ec.jpg)