本文實例講述了ThinkPHP5&5.1實現驗證碼的生成、使用及點擊刷新功能。分享給大家供大家參考,具體如下:
驗證碼現在是用戶登錄、支付等很多環節的必備元素,ThinkPHP5&5.1給我們提供了驗證碼的生成方式,也是非常的簡單,在這里寫一個完整的驗證碼驗證的使用方法,供大家參考。
前臺用戶在登錄時候需要驗證碼驗證才能登錄。首先使用Composer安裝think-captcha擴展包:
1
|
composer require topthink /think-captcha |
在需要顯示驗證碼的地方:
1
2
3
4
5
6
7
|
< tr > < th >請輸入驗證碼:</ th > < td > < input type = "text" name = "captcha" class = "inp01" /> < img src = "{:url('index/login/verify')}" alt = "驗證碼加載中" id = "captcha" /> </ td > </ tr > |
其中verify是生成驗證碼的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public function verify() { $config = [ // 驗證碼字體大小 'fontSize' => 15, // 驗證碼位數 'length' => 3, // 關閉驗證碼雜點 'useNoise' => false, ]; $captcha = new \think\captcha\Captcha( $config ); return $captcha ->entry(); } |
其中$config是驗證碼的配置項,具體有哪些配置內容可以參考手冊。
使用Ajax或者jquery-validate進行驗證碼的驗證,也可以提交以后進行驗證:
1
2
3
4
5
6
7
8
9
10
|
public function checkcapcha() { $captcha = new \think\captcha\Captcha(); if ( ! $captcha ->check(input( 'post.captcha' ))) { return false; } else { return true; } } |
為了實現點擊驗證碼刷新的功能,還要寫js代碼:
1
2
3
|
$( "#captcha" ).click( function (event) { this .src = "{:url('index/login/verify')}?" +Math.random(); }); |
這樣就實現了驗證碼的驗證功能,是不是非常簡單?
希望本文所述對大家基于ThinkPHP框架的PHP程序設計有所幫助。
原文鏈接:https://blog.csdn.net/pan_yuyuan/article/details/81947804