注意需要先把php_gd2.dll放开:
php.ini文件修改。
如下验证码效果:
代码如下:
Captcha.php
<?php
namespace vendor;
class Captcha{
public static function getCaptcha($width = 450, $height = 65, $length = 4, $fonts = ""){
if(empty($fonts)){
$fonts = 'captcha.ttf';
}
$fonts = __DIR__ . "/fonts/" . $fonts;
$img = imagecreatetruecolor($width, $height);
$bgColor = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imagefill($img, 0, 0, $bgColor);
// //增加干扰
for($i = 0; $i < 50; $i++){
$dotsColor = imagecolorallocate($img, mt_rand(140, 190), mt_rand(140, 190), mt_rand(140, 190));
imagestring($img,mt_rand(1, 5), mt_rand(0, $width), mt_rand(0, $height), "*", $dotsColor);
}
for($i = 0; $i < 15; $i++){
$lineColor = imagecolorallocate($img, mt_rand(80, 130), mt_rand(80, 130), mt_rand(80, 130));
imageline($img, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $lineColor);
}
//
$captcha = self::getString($length);
@session_start();
$_SESSION["captcha"] = $captcha;
for($i = 0; $i < $length; $i++){
$cColor = imagecolorallocate($img, mt_rand(15, 25), mt_rand(15, 25), mt_rand(15, 25));
imagettftext($img, mt_rand(15, 25), mt_rand(-45, 45), $width / ($length + 1) * ($i + 1),
mt_rand(25, $height -25), $cColor, $fonts, $captcha[$i]);
}
header("Content-type:image/png");
imagepng($img);
imagedestroy($img);
}
private static function getString($length = 4): string{
$captcha = "";
for($i = 0; $i < $length; $i++){
switch(mt_rand(1, 3)){
case 1: //49-57代表1-9
$captcha .= chr(mt_rand(49, 57));
break;
case 2: //65-90代表a-z
$captcha .= chr(mt_rand(65, 90));
break;
case 3: //97-122代表A-Z
$captcha .= chr(mt_rand(97, 122));
break;
}
}
return $captcha;
}
}
这里我的调用是这样的:
public function captcha(){
Captcha::getCaptcha();
}
就可以了。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://it1995.blog.csdn.net/article/details/122790912
内容来源于网络,如有侵权,请联系作者删除!