之前公司寫圖片驗證碼時用的是session
后來寫接口時也想用session存驗證碼 不過領導說RESTful API 寫接口 沒有session這一說 於是就用了redis 存驗證碼
還有就是接口需要返回值
不能直接把圖片顯示出來 這時需要對圖片驗證碼進行base64轉碼處理 返回base64的值 然后他們前端再調用
===================================================================================================================
在Thinkphp框架里找了個驗證碼類 修改了一下
生成驗證碼(字體文件可以去thinkphp框架里提取):
<?php
/**
*@descrption : 驗證碼生成類
*@author : Mark.liu
*/
date_default_timezone_set('PRC');
require_once('/data/redis/RedisConfig.php');
class Verify {
protected $config = array(
'seKey' => '888888', // 驗證碼加密密鑰
'codeSet' => '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY', // 驗證碼字符集合
'expire' => 1800, // 驗證碼過期時間(s)
'useZh' => false, // 使用中文驗證碼
'zhSet' => '', // 中文驗證碼字符串
'useImgBg' => false, // 使用背景圖片
'fontSize' => 25, // 驗證碼字體大小(px)
'useCurve' => true, // 是否畫混淆曲線
'useNoise' => true, // 是否添加雜點
'imageH' => 0, // 驗證碼圖片高度
'imageW' => 0, // 驗證碼圖片寬度
'length' => 5, // 驗證碼位數
'fontttf' => '', // 驗證碼字體,不設置隨機獲取
'bg' => array(243, 251, 254), // 背景顏色
'reset' => true, // 驗證成功后是否重置
);
private $_image = NULL; // 驗證碼圖片實例
private $_color = NULL; // 驗證碼字體顏色
/**
* 架構方法 設置參數
* @access public
* @param array $config 配置參數
*/
public function __construct($config=array()){
$this->config = array_merge($this->config, $config);
}
/**
* 使用 $this->name 獲取配置
* @access public
* @param string $name 配置名稱
* @return multitype 配置值
*/
public function __get($name) {
return $this->config[$name];
}
/**
* 設置驗證碼配置
* @access public
* @param string $name 配置名稱
* @param string $value 配置值
* @return void
*/
public function __set($name,$value){
if(isset($this->config[$name])) {
$this->config[$name] = $value;
}
}
/**
* 檢查配置
* @access public
* @param string $name 配置名稱
* @return bool
*/
public function __isset($name){
return isset($this->config[$name]);
}
/**
* redis連接
* @return
*/
public function _redis()
{
$redis = new Redis;
$hosts = RedisServerConfig::SERVER_HOST;
$port = RedisServerConfig::SERVER_PORT;
$pwd = RedisServerConfig::SERVER_PASS;
$redis->connect($hosts,$port);
$redis->auth($pwd);
return $redis;
}
/**
* 驗證驗證碼是否正確
* @access public
* @param string $code 用戶驗證碼
* @param string $id 驗證碼標識
* @return bool 用戶驗證碼是否正確
*/
public function check($code, $id = '') {
$key = $this->authcode($this->seKey).$id;
$redis = $this->_redis();
$_val = $redis->get($key);
if(empty($_val))
{
return false;
}
$secode = json_decode($_val,true);
if(empty($code) || empty($secode)) {
return false;
}
// session 過期
$NOW_TIME = time();
if($NOW_TIME - $secode['verify_time'] > $this->expire) {
// unset($_SESSION[$key]);
$redis->expire($key,0);
// session($key, null);
return false;
}
if($this->authcode(strtoupper($code)) == $secode['verify_code']) {
// $this->reset && session($key, null);
// unset($_SESSION[$key]);
$redis->expire($key,0);
return true;
}
return false;
}
/**
* 輸出驗證碼並把驗證碼的值保存的session中
* 驗證碼保存到session的格式為: array('verify_code' => '驗證碼值', 'verify_time' => '驗證碼創建時間');
* @access public
* @param string $id 要生成驗證碼的標識
* @return void
*/
public function entry($id = '') {
// 圖片寬(px)
$this->imageW || $this->imageW = $this->length*$this->fontSize*1.5 + $this->length*$this->fontSize/2;
// 圖片高(px)
$this->imageH || $this->imageH = $this->fontSize * 2.5;
// 建立一幅 $this->imageW x $this->imageH 的圖像
$this->_image = imagecreate($this->imageW, $this->imageH);
// 設置背景
imagecolorallocate($this->_image, $this->bg[0], $this->bg[1], $this->bg[2]);
// 驗證碼字體隨機顏色
$this->_color = imagecolorallocate($this->_image, mt_rand(1,150), mt_rand(1,150), mt_rand(1,150));
// 驗證碼使用隨機字體
$ttfPath = dirname(__FILE__) . '/Verify/' . ($this->useZh ? 'zhttfs' : 'ttfs') . '/';
if(empty($this->fontttf)){
$dir = dir($ttfPath);
$ttfs = array();
while (false !== ($file = $dir->read())) {
if($file[0] != '.' && substr($file, -4) == '.ttf') {
$ttfs[] = $file;
}
}
$dir->close();
$this->fontttf = $ttfs[array_rand($ttfs)];
}
$this->fontttf = $ttfPath . $this->fontttf;
if($this->useImgBg) {
$this->_background();
}
if ($this->useNoise) {
// 繪雜點
$this->_writeNoise();
}
if ($this->useCurve) {
// 繪干擾線
$this->_writeCurve();
}
// 繪驗證碼
$code = array(); // 驗證碼
$codeNX = 0; // 驗證碼第N個字符的左邊距
if($this->useZh){ // 中文驗證碼
for ($i = 0; $i<$this->length; $i++) {
$code[$i] = iconv_substr($this->zhSet,floor(mt_rand(0,mb_strlen($this->zhSet,'utf-8')-1)),1,'utf-8');
imagettftext($this->_image, $this->fontSize, mt_rand(-40, 40), $this->fontSize*($i+1)*1.5, $this->fontSize + mt_rand(10, 20), $this->_color, $this->fontttf, $code[$i]);
}
}else{
for ($i = 0; $i<$this->length; $i++) {
$code[$i] = $this->codeSet[mt_rand(0, strlen($this->codeSet)-1)];
$codeNX += mt_rand($this->fontSize*1.2, $this->fontSize*1.6);
imagettftext($this->_image, $this->fontSize, mt_rand(-40, 40), $codeNX, $this->fontSize*1.6, $this->_color, $this->fontttf, $code[$i]);
}
}
// 保存驗證碼
$key = $this->authcode($this->seKey);
$code = $this->authcode(strtoupper(implode('', $code)));
$secode = array();
$secode['verify_code'] = $code; // 把校驗碼保存到session
$secode['verify_time'] = time(); // 驗證碼創建時間
$redis = $this->_redis();
$redis->set($key.$id,json_encode($secode));
header('Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
ob_start();
imagepng($this->_image);
$image_data = ob_get_contents();
ob_end_clean();
//$base64 = base64_encode($imagedata);
$image_data_base64 = 'data:image/png;base64,'.base64_encode ($image_data);
return $image_data_base64;
}
/**
* 畫一條由兩條連在一起構成的隨機正弦函數曲線作干擾線(你可以改成更帥的曲線函數)
*
* 高中的數學公式咋都忘了涅,寫出來
* 正弦型函數解析式:y=Asin(ωx+φ)+b
* 各常數值對函數圖像的影響:
* A:決定峰值(即縱向拉伸壓縮的倍數)
* b:表示波形在Y軸的位置關系或縱向移動距離(上加下減)
* φ:決定波形與X軸位置關系或橫向移動距離(左加右減)
* ω:決定周期(最小正周期T=2π/∣ω∣)
*
*/
private function _writeCurve() {
$px = $py = 0;
// 曲線前部分
$A = mt_rand(1, $this->imageH/2); // 振幅
$b = mt_rand(-$this->imageH/4, $this->imageH/4); // Y軸方向偏移量
$f = mt_rand(-$this->imageH/4, $this->imageH/4); // X軸方向偏移量
$T = mt_rand($this->imageH, $this->imageW*2); // 周期
$w = (2* M_PI)/$T;
$px1 = 0; // 曲線橫坐標起始位置
$px2 = mt_rand($this->imageW/2, $this->imageW * 0.8); // 曲線橫坐標結束位置
for ($px=$px1; $px<=$px2; $px = $px + 1) {
if ($w!=0) {
$py = $A * sin($w*$px + $f)+ $b + $this->imageH/2; // y = Asin(ωx+φ) + b
$i = (int) ($this->fontSize/5);
while ($i > 0) {
imagesetpixel($this->_image, $px + $i , $py + $i, $this->_color); // 這里(while)循環畫像素點比imagettftext和imagestring用字體大小一次畫出(不用這while循環)性能要好很多
$i--;
}
}
}
// 曲線后部分
$A = mt_rand(1, $this->imageH/2); // 振幅
$f = mt_rand(-$this->imageH/4, $this->imageH/4); // X軸方向偏移量
$T = mt_rand($this->imageH, $this->imageW*2); // 周期
$w = (2* M_PI)/$T;
$b = $py - $A * sin($w*$px + $f) - $this->imageH/2;
$px1 = $px2;
$px2 = $this->imageW;
for ($px=$px1; $px<=$px2; $px=$px+ 1) {
if ($w!=0) {
$py = $A * sin($w*$px + $f)+ $b + $this->imageH/2; // y = Asin(ωx+φ) + b
$i = (int) ($this->fontSize/5);
while ($i > 0) {
imagesetpixel($this->_image, $px + $i, $py + $i, $this->_color);
$i--;
}
}
}
}
/**
* 畫雜點
* 往圖片上寫不同顏色的字母或數字
*/
private function _writeNoise() {
$codeSet = '2345678abcdefhijkmnpqrstuvwxyz';
for($i = 0; $i < 10; $i++){
//雜點顏色
$noiseColor = imagecolorallocate($this->_image, mt_rand(150,225), mt_rand(150,225), mt_rand(150,225));
for($j = 0; $j < 5; $j++) {
// 繪雜點
imagestring($this->_image, 5, mt_rand(-10, $this->imageW), mt_rand(-10, $this->imageH), $codeSet[mt_rand(0, 29)], $noiseColor);
}
}
}
/**
* 繪制背景圖片
* 注:如果驗證碼輸出圖片比較大,將占用比較多的系統資源
*/
private function _background() {
$path = dirname(__FILE__).'/Verify/bgs/';
$dir = dir($path);
$bgs = array();
while (false !== ($file = $dir->read())) {
if($file[0] != '.' && substr($file, -4) == '.jpg') {
$bgs[] = $path . $file;
}
}
$dir->close();
$gb = $bgs[array_rand($bgs)];
list($width, $height) = @getimagesize($gb);
// Resample
$bgImage = @imagecreatefromjpeg($gb);
@imagecopyresampled($this->_image, $bgImage, 0, 0, 0, 0, $this->imageW, $this->imageH, $width, $height);
@imagedestroy($bgImage);
}
/* 加密驗證碼 */
private function authcode($str){
$key = substr(md5($this->seKey), 5, 8);
$str = substr(md5($str), 8, 10);
return md5($key . $str);
}
}
調用生成圖片驗證碼:
<?php $codeId = 1; //可以根據不同使用場景傳不同的ID $infos = new Verify; $base64Data = $infos->entry($codeId); $returnData = [ 'imgSrc'=>$base64Data ];
校驗驗證碼:
<?php
$verifyCode = new Verify;
if(!$verifyCode->check($confirmCode,$confirmCodeId))
{
echo '驗證碼錯誤';
}
