首先使用Composer安装think-captcha扩展包:
composer require topthink/think-captcha
控制器引入
use think\captcha\facade\Captcha;
开启session
代码如下:
1 <?php 2 namespace app\controller; 3 4 use app\BaseController; 5 use think\captcha\facade\Captcha; 6 7 class Food extends BaseController { 8 9 // 模版 10 public function show() { 11 return view(); 12 } 13 14 // 生成常规验证码 15 public function verify() { 16 return Captcha::create(); 17 } 18 19 // 验证验证码是否正确 20 public function test() { 21 $code = input('code'); 22 // 检测输入的验证码是否正确,$code为用户输入的验证码字符串 23 if (!captcha_check($code)) { 24 echo "验证失败"; 25 } else { 26 echo "成功"; 27 } 28 } 29 }
视图:show.html
<!DOCTYPE html> <html> <head> <title></title> <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script> </head> <style type="text/css"> input { height: 30px; line-height: 30px; } </style> <body> <form action="test" method="post"> <table> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密 码</td> <td><input type="text" name="pwd"></td> </tr> <tr> <td>验证码</td> <td><input type="text" name="code"> <img id="codePic" height="30px" src="{:url('food/verify')}" onclick="flush()"> </td> </tr> <tr> <td> <button>注册</button> </td> </tr> </table> </form> </body> </html> <script type="text/javascript"> function flush() { $("#codePic").attr("src","{:url('food/verify')}?flag="+Math.random()); } </script>
效果图: