ThinkPHP中已经提供了验证码的生成以及验证的功能。下面介绍如何使用验证码。编程的时候还是采用MVC的方式
View层
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="{$smarty.const.__SELF__}" method="post">
用户名:<input type="text" name="username"/><br/>
密 码:<input type="password" name="password"/><br/>
验证码:<input type="text" name="code"/>
<img src="http://localhost/CloudTemp/index.php/Home/Index/vertifyImg" alt=""/><br/>
<button type="submit">提交</button>
</form>
</body>
</html>
模版引擎采用smarty,__SELF__表示自身的URL,即表单提交给自己
Model层
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2016/6/27
* Time: 9:14
*/ namespace Home\Model;
use Think\Model; class ManageModel extends Model{
function checkNamePwd($name, $pwd){
$userpwd = $this->getFieldByUsername($name, 'userpwd');
if($userpwd != null && $userpwd == $pwd)
return true;
else
return false;
}
}
model层对用户提交的用户名和密码进行数据匹配查询,如果一致,则返回true。
Controller层
<?php
namespace Home\Controller;
use Think\Controller;
use Home\Model\ManageModel;
class IndexController extends Controller { public function vertifyImg(){
$config = array(
'fontSize' => 15, // 验证码字体大小
'length' => 4, // 验证码位数
'useNoise' => false, // 开启验证码杂点
'imageH' => 30,
'imageW' => 110,
'fontttf' => '4.ttf'
);
$Verify = new \Think\Verify($config);
$Verify->entry();
} public function login(){
if(empty($_POST))
$this->display();
else{
if($this->checkVerify($_POST['code'])){
$user = new ManageModel('user');
$res = $user->checkNamePwd($_POST['username'], $_POST['password']);
if($res == true){
session('username', $_POST['username']);
session('password', $_POST['password']);
echo 'ok';
}
else
$this->display();
} else
$this->display();
}
}
private function checkVerify($code, $id = ''){
$verify = new \Think\Verify();
return $verify->check($code, $id);
}
}
在controller层生成验证码,用户身份检查。如果用户输入的用户名、密码、验证码正确则将用户名和密码保存到session中,并返回OK,否则返回登录页面。