Docker PHP中安装gd扩展并生成图形验证码

发布时间 2023-11-15 15:10:00作者: Don

在容器中执行:

apt install libjpeg62-turbo-dev libfreetype6-dev -y

docker-php-ext-configure gd --enable-gd --with-freetype --with-jpeg

docker-php-ext-install gd

可运行:php --ri gd 查看安装结果,重启docker容器。

图形验证码示例代码:

<?php
session_start();
function random($len) {
    $srcstr = "123456789ABCDEFGHJKLNPQRSTUVXYZ";
    $strs = "";
    for ($i = 0; $i < $len; $i++) {
        $strs .= $srcstr[mt_rand(0,30)];
    }
    return $strs;
}
 
//随机生成的字符串
$str = random(5); 
 
//验证码图片的宽度
$width  = 80;      
 
//验证码图片的高度
$height = 40;     
 
//声明需要创建的图层的图片格式
@ header("Content-Type:image/png");
 
//创建一个图层
$im = imagecreate($width, $height);
 
//背景色
$back = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
 
//模糊点颜色
$pix  = imagecolorallocate($im, 100, 207, 95);
 
//字体色
$color = imagecolorallocate($im, 100, 207, 2);

//边框颜色
$col = imagecolorallocate($im, 100, 164, 26);

//字体
putenv('GDFONTPATH=' . realpath('.'));//解决linux下GD库版本低于2.0.18不能显示的问题
$font = 'arial.ttf';
 
//绘模糊作用的点
mt_srand();
for ($i = 0; $i < 800; $i++) {
    imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $pix);
}
 
//输出字符
imagettftext($im, 16, 0, 5, 28, $color, $font, $str);

//输出矩形
imagerectangle($im, 0, 0, $width -1, $height -1, $col);
 
//输出图片
imagepng($im);
 
imagedestroy($im);
 
$str = md5(strtolower($str));
 
//选择 Session
$_SESSION["verification"] = $str;
?>