好久没有写文章了,最近有时间,正好在折腾给 WordPress 登录后台添加一个字符图片验证码功能,效果图如下,感兴趣的小伙伴可以自己折腾一下。
1. functions.php 加入以下代码
/**
* 生成图片验证码
*/
function generate_image_captcha() {
// 启动session(如果尚未启动)
if (!session_id()) {
session_start();
}
// 验证码配置
$width = 120;
$height = 40;
$font_size = 20;
$chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; // 去掉了容易混淆的字符
$captcha_length = 4;
// 生成随机验证码
$captcha = '';
for ($i = 0; $i < $captcha_length; $i++) {
$captcha .= $chars[rand(0, strlen($chars) - 1)];
}
// 存储验证码到session
$_SESSION['login_captcha'] = strtolower($captcha);
// 创建图片
$image = imagecreatetruecolor($width, $height);
// 颜色定义
$bg_color = imagecolorallocate($image, 245, 245, 245); // 背景色
$text_color = imagecolorallocate($image, 0, 0, 0); // 黑色文字
$noise_color = imagecolorallocate($image, 100, 120, 180); // 干扰线颜色
// 填充背景
imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);
// 添加干扰线(5条随机线)
for ($i = 0; $i < 5; $i++) {
imageline($image,
rand(0, $width), rand(0, $height),
rand(0, $width), rand(0, $height),
$noise_color);
}
// 添加噪点(100个随机像素点)
for ($i = 0; $i < 100; $i++) {
imagesetpixel($image,
rand(0, $width), rand(0, $height),
$noise_color);
}
// 计算文本位置(居中)
$textbox = imagettfbbox($font_size, 0, __DIR__.'/diy/fonts/Arial.ttf', $captcha);
$x = ($width - $textbox[4]) / 2;
$y = ($height - $textbox[5]) / 2;
// 添加文字(每个字符不同位置和角度)
for ($i = 0; $i < $captcha_length; $i++) {
$angle = rand(-10, 10);
$char_x = $x + ($i * ($font_size + 5));
$char_y = $y + rand(-5, 5);
imagettftext($image, $font_size, $angle,
$char_x, $char_y,
$text_color, __DIR__.'/diy/fonts/Arial.ttf',
$captcha[$i]);
}
// 输出图片
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
exit;
}
/**
* 添加验证码字段(美化版)
*/
function add_beautiful_captcha_to_login() {
$captcha_url = site_url('?generate_captcha=1&t='.time());
echo '<div class="captcha-container">
<label for="image_captcha">验证码</label>
<div class="captcha-row">
<input type="text" name="image_captcha" id="image_captcha"
class="input" value="" size="20" required
autocomplete="off" autocapitalize="off">
<img src="'.$captcha_url.'" alt="CAPTCHA" class="captcha-image"
onclick="this.src=\''.site_url('?generate_captcha=1&t=').'\' + Date.now()">
</div>
</div>';
}
add_action('login_form', 'add_beautiful_captcha_to_login');
/**
* 验证验证码(修正版)
*/
function verify_image_captcha($user, $password) {
// 确保session已启动
if (!session_id()) {
session_start();
}
// 优先验证验证码(如果验证码错误,直接返回,不继续验证账号密码)
$user_input = isset($_POST['image_captcha']) ? strtolower(trim($_POST['image_captcha'])) : '';
$correct_captcha = isset($_SESSION['login_captcha']) ? $_SESSION['login_captcha'] : '';
// 清除已使用的验证码(无论对错)
unset($_SESSION['login_captcha']);
// 验证码为空时的错误
if (empty($user_input)) {
return new WP_Error('captcha_empty', __('<strong>错误</strong>: 请输入验证码'));
}
// 验证码不匹配时的错误
if ($user_input !== $correct_captcha) {
return new WP_Error('captcha_failed', __('<strong>错误</strong>: 验证码不正确'));
}
// 如果验证码正确,继续原有的账号密码验证
return $user;
}
add_filter('wp_authenticate_user', 'verify_image_captcha', 10, 2);
/**
* 处理验证码图片生成请求
*/
function handle_captcha_generation() {
if (isset($_GET['generate_captcha'])) {
generate_image_captcha();
}
}
add_action('init', 'handle_captcha_generation');
/**
* 初始化session
*/
function start_captcha_session() {
if (!session_id() && !headers_sent()) {
session_start();
}
}
add_action('init', 'start_captcha_session', 1);
2. 检查 GD 库是否安装并启用
使用命令行检查
如果您有服务器 SSH 访问权限:
php -m | grep -i gd
或者:
php -i | grep -i gd
如果返回包含 “gd” 的结果,则表示已安装。
如果没有包含则继续下一步安装 GD 库。
3. 安装 GD 库
对于 Debian/Ubuntu:
sudo apt-get install php-gd
对于 CentOS/RHEL:
sudo yum install php-gd
安装完成后最好重启一下服务器
4. 下载字体文件
地址: https://pan.baidu.com/s/1VEL1zT3GUcG3bIAYgPJxDQ 提取码: 4x5c
代码中使用了__DIR__.'/diy/fonts/Arial.ttf'
指定字体文件路径。
确保下载的字体文件 arial.ttf 已上传到 主题根目录下 /diy/fonts 文件夹中,这里也可以自己指定。
设置字体文件权限:
chmod 644 Arial.ttf
5. WordPress 后台登录页面美化
将下面代码复制到 functions.php 文件中
/** * WordPress 登录页面全面美化 */ function custom_login_page_styles() { // 自定义CSS样式 echo '<style type="text/css"> /* 整体页面样式 */ body.login { background-color: #f8f9fa; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; } /* 登录框样式 */ #login { width: 380px; padding: 5% 0 0; margin: 0 auto; } .login h1 a { background-size: contain; width: 100%; height: 80px; margin-bottom: 20px; } /* 表单样式 */ .login form { border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); border: none; padding: 30px; background: #fff; } /* 输入框样式 */ .login input[type="text"], .login input[type="password"] { border: 1px solid #ddd; border-radius: 4px; padding: 12px 15px; font-size: 15px; height: auto; box-shadow: none; transition: all 0.3s; } .login input[type="text"]:focus, .login input[type="password"]:focus { border-color: #4d96ff; box-shadow: 0 0 0 2px rgba(77, 150, 255, 0.2); } /* 按钮样式 */ .wp-core-ui .button-primary { background: #4d96ff; border: none; box-shadow: none; text-shadow: none; border-radius: 4px; padding: 1px 20px !important; height: auto; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; font-size: 16px; transition: all 0.3s; } .wp-core-ui .button-primary:hover { background: #3a7de0; } /* 验证码区域样式 */ .captcha-row { display: flex; gap: 10px; } #image_captcha { flex: 1; padding: 12px 15px; border: 1px solid #ddd; border-radius: 4px; font-size: 15px; height: auto; } .captcha-image { width: 120px; height: 46px; border: 1px solid #eee; border-radius: 4px; background: #f5f7fa; cursor: pointer; transition: all 0.3s; } .captcha-image:hover { opacity: 0.9; } .captcha-description { margin: 8px 0 0; color: #646970; font-size: 13px; } /* 页脚链接样式 */ .login #nav, .login #backtoblog { text-align: center; padding: 0; margin: 20px 0 0; } .login #nav a, .login #backtoblog a { color: #646970; transition: color 0.3s; } .login #nav a:hover, .login #backtoblog a:hover { color: #4d96ff; } /* 响应式调整 */ @media screen and (max-width: 480px) { #login { padding: 20% 0 0; } } </style>'; } add_action('login_head', 'custom_login_page_styles');
到此教程结束!