You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.9 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Http\Controllers\API;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;
class ImageVerificationController
{
public function GetCode()
{
// 可用字符(排除 0, o, O, i, I, l, 1
$characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
$length = 4;
$captcha = '';
for ($i = 0; $i < $length; $i++) {
$captcha .= $characters[rand(0, strlen($characters) - 1)];
}
// 创建画布宽120高40背景白色
$width = 160;
$height = 70;
$image = Image::canvas($width, $height, '#ffffff');
// 使用 GD 内置字体(无需 .ttf 文件)
// font(5) 表示使用内置字体大小 5最大
$image->text($captcha, $width / 2, $height / 2, function ($font) {
$font->file(public_path('COOPBL.TTF'));
$font->size(40); // GD 内置字体只支持 1-5
$font->color('#000000');
$font->align('center');
$font->valign('middle');
});
// 添加干扰点(杂色)
for ($i = 0; $i < 150; $i++) {
$x = rand(0, $width);
$y = rand(0, $height);
$color = '#' . str_pad(dechex(rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
$image->pixel($color, $x, $y);
}
for ($i = 0; $i < 3; $i++) {
$image->line(
rand(0, $width), rand(0, $height),
rand(0, $width), rand(0, $height),
function ($draw) {
$draw->color('#' . str_pad(dechex(rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT));
// 移除了设置宽度的部分
}
);
}
// 转为 Base64
$base64 = 'data:image/png;base64,' . base64_encode($image->encode('png'));
$id=DB::table('yanzhengma_image')->insertGetId([
'code' => $captcha,
'end_time' => date('Y-m-d H:i:s', strtotime('+5 minutes')),
'created_at' => date('Y-m-d H:i:s'),
]);
if($id){
return \Yz::Return(true,'获取成功',[
'image' => $base64,
'code_id' => $id,
// 注意:生产环境不要返回明文验证码!仅用于调试
//'debug_captcha' => $captcha,
]);
}else{
return \Yz::echoError1('验证码获取失败');
}
}
public function CheckCode(){
$code_id = request('code_id');
$code = request('code');
$check=DB::table('yanzhengma_image')
->where('id',$code_id)
->where('code',$code)
->where('end_time','>',date('Y-m-d H:i:s'))
->where('status','1')
->update([
'status'=>'2'
]);
if($check){
return \Yz::Return(true,'验证成功');
}else{
return \Yz::echoError1('验证码无效');
}
}
}