PHP-簡單驗證碼類
阿新 • • 發佈:2019-01-24
<?php
/**
* 封裝一個輸出隨機驗證碼的類
*/
class Verify {
public $config = array(
'width' => 70,
'height' => 45,
'size' => 20,
'startx' => 10,
'starty' => 35,
'font' => '..//public/font/verdana.ttf'
);
/**
* 初始化,建構函式的傳入陣列值,可以改變我們的config內容
* @param $arr
*/
public function __construct($arr = null)
{
if (is_array($arr)) {
foreach ($arr as $key => $value) {
if (array_key_exists($key, $this->config)) {
$this->config[$key] = $value;
}
}
}
}
public function showVc() {
header('content-type:image/png'); //畫布正確顯示的header頭
//首先建立一個畫布,所有的圖形操作都是在畫布的基礎上展示的,定義寬高
$draw = imagecreate($this->config['width'], $this->config['height']);
//給畫布上色
imagecolorallocate($draw, mt_rand(50, 180), mt_rand(20, 180), mt_rand(50, 180));
//增加一些畫素點pixel,干擾識別
//為隨機字型和干擾的點,線進行顏色的設定
$pixelcolor = imagecolorallocate($draw, mt_rand(0, 80), mt_rand(0, 80), mt_rand(0, 80));
$linecolor = imagecolorallocate($draw, mt_rand(100, 230), mt_rand(100, 200), mt_rand(100, 200));
$fontcolor = imagecolorallocate($draw, mt_rand(100, 160), mt_rand(100, 200), mt_rand(100, 170));
//然後把這些干擾專案畫在畫布上
for ($j = 0; $j < 100; $j++) {
imagesetpixel($draw, mt_rand(0, $this->config['width']), mt_rand(0, $this->config['height']), $pixelcolor);
if ($j < 4) {
//畫線
imageline($draw, mt_rand(0, $this->config['width'] / 5), mt_rand(0, $this->config['height']), mt_rand($this->config['width'] / 2, $this->config['width']), mt_rand(0, $this->config['height']), $linecolor);
}
}
imagettftext($draw, $this->config['size'],10, $this->config['startx'], $this->config['starty'],$fontcolor, $this->config['font'], $this->getRandData());
//輸出畫布
imagepng($draw);
}
/**
* 返回隨機字元
* @return string
*/
public function getRandData(){
$arr1 = range('A','Z');
$arr2 = range(1,9);
$arr3 = range('a','z');
$arr4 = array_merge($arr1,$arr2,$arr3);
$strData ="";
for($i=0;$i<4;$i++){
$index = array_rand($arr4);
$strData.=$arr4[$index];
}
$_SESSION['vc'] = $strData;
return $strData;
}
}