在thinkphp中使用验证码很容易,只要调用thinkphp现有的方法就可以。当然,php的GD库肯定是要开的(就是在php.ini中要加载gd模块)。
thinkphp 3.1
----------------------------------------------------------------------------------------------
首先,在写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>
thinkphp 3.2
------------------------------------------------------------------------------------------------------------
首先,在写控制器文件,如:IndexController.class.php.
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends HomeController {
//显示验证码
public function index(){
$this->display();
}
// 生成验证码
public function verify() {
$verify = new \Think\Verify();
$verify->entry(1);
}
}
?>
在对应的模板文件:Views\Index\目录下新建文件index.html,内容如下:
<script type=‘text/javascript‘>
//重载验证码
function freshVerify() {
document.getElementById(‘verifyImg‘).src=‘{:U("Index/verify")}?‘+Math.random();
}
</script>
<form method=‘post‘ action=‘__URL__/verifyCheck‘>
<input type=‘text‘ name=‘verifyTest‘>
<img style=‘cursor:pointer‘ title=‘刷新验证码‘ src=‘{:U("Index/verify")}‘ id=‘verifyImg‘ onClick=‘freshVerify()‘/>
<button type=‘submit‘>确定</button>
</form>