改寫驗证碼類,實現加法驗证碼
使用TP自帶的驗证碼類,改寫實現加法驗证碼及驗证。
/**
* 加法驗证碼
*/
public function add_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(); // 驗证碼
$text_str = '';
$sum = 0;
for($i=0;$i < $this->length;$i++){
$tmp= mt_rand(1,10);
if($i == $this->length-1 ){
$text_str .= $tmp.'=';
$sum += $tmp;
}else{
$text_str .= $tmp.'+';
$sum += $tmp;
}
}
$code = $text_str;
imagettftext($this->_image, $this->fontSize, 0, $this->fontSize*0.7, $this->fontSize*1.7, $this->_color, $this->fontttf, $code);
// 保存驗证碼
$key = $this->authcode($this->seKey);
$secode = array();
$secode['verify_code'] = $sum; // 把校驗碼保存到session
$secode['verify_time'] = NOW_TIME; // 驗证碼創建時間
session($key.$id, $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');
header("content-type: image/png");
// 輸出圖像
imagepng($this->_image);
imagedestroy($this->_image);
}
當然驗证的方法也需要修改
/**
* 加法驗证碼的驗证
*/
public function add_check($code, $id = '') {
$key = $this->authcode($this->seKey).$id;
// 驗证碼不能爲空
$secode = session($key);
if(empty($code) || empty($secode)) {
return false;
}
// session 過期
if(NOW_TIME - $secode['verify_time'] > $this->expire) {
session($key, null);
return false;
}
if(intval($code) == $secode['verify_code']) {
$this->reset && session($key, null);
return true;
}
return false;
}
調用的方法
public function test4(){
$config = array(
'fontSize' => 16, // 驗证碼字體大小
'length' => 4, // 驗证碼位數
'useNoise' => false, // 關閉驗证碼雜點
'fontttf' => '2.ttf',// 字體
);
$Verify = new \Think\Verify($config);
$Verify->add_entry();
}只嘗試了一種思路,不是太完善。