注意需要先把PHP_gd2.dll放开:
如下验证码效果:
代码如下:
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();
}
就可以了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。