ThinkPHP中已经提供了验证码的生成以及验证的功能。下面介绍如何使用验证码。编程的时候还是采用MVC的方式
View层
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form action="{$smarty.const.__SELF__}" method="post"> 9 用户名:<input type="text" name="username"/><br/> 10 密 码:<input type="password" name="password"/><br/> 11 验证码:<input type="text" name="code"/> 12 <img src="http://localhost/CloudTemp/index.php/Home/Index/vertifyImg" alt=""/><br/> 13 <button type="submit">提交</button> 14 </form> 15 </body> 16 </html>
模版引擎采用smarty,__SELF__表示自身的URL,即表单提交给自己
Model层
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2016/6/27 * Time: 9:14 */ namespace HomeModel; use ThinkModel; 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 HomeController; use ThinkController; use HomeModelManageModel; class IndexController extends Controller { public function vertifyImg(){ $config = array( 'fontSize' => 15, // 验证码字体大小 'length' => 4, // 验证码位数 'useNoise' => false, // 开启验证码杂点 'imageH' => 30, 'imageW' => 110, 'fontttf' => '4.ttf' ); $Verify = new ThinkVerify($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 ThinkVerify(); return $verify->check($code, $id); } }
在controller层生成验证码,用户身份检查。如果用户输入的用户名、密码、验证码正确则将用户名和密码保存到session中,并返回OK,否则返回登录页面。