PHP如何實現算術驗證碼功能

本篇文章扣丁學堂PHP培訓小編給讀者們分享一下PHP如何實現算術驗證碼功能,文中有代碼列出供大家參考學習,希望和小夥伴們共同參考。

PHP如何實現算術驗證碼功能

扣丁學堂PHP培訓

php代碼如下:實現驗證碼的功能:

/**
* @param int $width 寬度,默認為120
* @param int $height 高度,默認為50
* @param int $fontSize 字體的大小
* @return 圖片資源
*/
function arithmeticCode($width=120,$height=50,$fontSize=20){
//開啟session
session_start();
//創建畫布
$img = imagecreatetruecolor($width,$height);
//分配顏色
$color = imagecolorallocate($img,255,255,255);
//填充顏色
imagefill($img,0,0,$color);
//干擾點
for ($i = 0;$i < 500;$i++){
$pixColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$pixColor);
}
//干擾線
for ($i = 0;$i < 4;$i++){
$lineColor = imagecolorallocate($img,mt_rand(0,120),mt_rand(0,120),mt_rand(0,120));
imageline($img,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$lineColor);
}
//定義一個數組存放運算符號
$arr = ['+','-','*'];
//計算數組的長度
$len = count($arr);
//定義一個1到20的數組
$num = range(1,20);
$numLen = count($num);
//定義一個空數組來存放隨機取得的驗證碼

$code = [];
for ($i = 0;$i < $len;$i++) {
if ($i == 1) {
$code[] = $arr[mt_rand(0,$len-1)];
}else {
$code[] = $num[mt_rand(0,$numLen-1)];
}
}
$str = implode($code);//將數組轉為字符串
$textColor = imagecolorallocate($img,mt_rand(100,200),mt_rand(100,200),mt_rand(100,200));
$fontAngle = 0;
$x = ($width - $fontSize*3)/2;
$y = ($height - $fontSize) / 2 + $fontSize;
imagettftext($img,$fontSize,$fontAngle,$x,$y,$textColor,"./img/msyh.ttc",$str);
$res = getRes($code);
//將函數存放在session中
$_SESSION['res'] = $res;
//輸出圖片
header("content-type:image/png");
imagepng($img);
}
/**
* @param $arr 一個包含運算符號的數組
* @return 返回一個運算結果
*/
function getRes($arr) {
$sum = 0;
//判斷數組元素下標為1的運算符號是什麼
switch ($arr[1]){
case '+':
$sum = $arr[0] + $arr[2];
break;
case '-':
$sum = $arr[0] - $arr[2];
break;
case '*':
$sum = $arr[0] * $arr[2];
break;
}
return $sum;
}
//調用函數
arithmeticCode(100,40,18);

html的部分代碼:





content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

<title>Document/<title>







test.php的測試:

session_start();
$res = $_SESSION['res'];
$value = $_GET['code'];
if ($res == $value) {
echo "test success";
}else{
echo "test fail";
}

想要了解更多關於PHP開發方面內容的小夥伴,請關注扣丁學堂PHP培訓官網、微信等平臺,扣丁學堂IT職業在線學習教育有專業的PHP講師為您指導,此外扣丁學堂老師精心推出的PHP視頻教程定能讓你快速掌握PHP從入門到精通開發實戰技能。

Pyhon基礎課程:https://ke.qq.com/course/327534?flowToken=1008607 【掃碼進入Python全棧開發免費公開課】

H5基礎課程:https://ke.qq.com/course/320523?flowToken=1008606【掃碼進入HTML5前端開發VIP免費公開課】


分享到:


相關文章: