使用php生成数学加减法验证码的核心做法是:在服务器端随机生成两个整数和一个运算符(加或减),计算正确答案,将答案存入session以便后续验证,同时将题目展示给前端。具体实现时,需确保数字范围合理以避免负数或过大结果,并配合gd库绘制图像。

如何生成并存储数学题与答案
通过随机函数生成操作数和运算符,计算结果后存入全局会话变量。rand()用于生成数字,$_SESSION用于持久化存储答案。此步骤不涉及图像绘制,仅处理逻辑数据。

<?php session_start();
// 设置数字范围
$num1 = rand(1, 50);
$num2 = rand(1, 50);
$operators = ['+', '-'];
$op = $operators[array_rand($operators)];
// 计算答案
if ($op === '+') {
$answer = $num1 + $num2;
} else {
// 防止负数,若结果为负则交换位置或重新生成
if ($num1 < $num2) {
$temp = $num1;
$num1 = $num2;
$num2 = $temp;
}
$answer = $num1 - $num2;
}
// 存储答案到Session
$_SESSION['math_captcha'] = $answer;
// 输出题目供前端显示(实际中通常返回JSON或直接嵌入HTML)
echo "{$num1} {$op} {$num2} = ?";
?>
如何使用GD库绘制验证码图像
利用PHP的GD扩展创建画布,写入文字,添加干扰元素,最后输出图像流。关键步骤包括初始化画布、设置字体颜色、绘制文本和噪点,以及发送正确的HTTP头信息。imagecreatetruecolor创建画布,imagestring或imagettftext绘制文字。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

<?php session_start();
header('Content-Type: image/png');
// 获取之前生成的题目和答案(实际应用中应结合前端请求参数)
// 这里假设已通过其他方式获取了 $num1, $op, $num2
// 为演示完整流程,重新生成并存储
$num1 = rand(1, 50);
$num2 = rand(1, 50);
$operators = ['+', '-'];
$op = $operators[array_rand($operators)];
if ($op === '+') {
$answer = $num1 + $num2;
} else {
if ($num1 < $num2) {
$temp = $num1;
$num1 = $num2;
$num2 = $temp;
}
$answer = $num1 - $num2;
}
$_SESSION['math_captcha'] = $answer;
// 构造题目字符串
$captcha_text = "{$num1}{$op}{$num2}";
// 创建画布
$width = 100;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 设置背景色
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);
// 设置文字颜色
$text_color = imagecolorallocate($image, 0, 0, 0);
// 绘制文字
imagestring($image, 5, 10, 10, $captcha_text, $text_color);
// 添加干扰点
for ($i = 0; $i < 50; $i++) {
$noise_color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($image, rand(0, $width), rand(0, $height), $noise_color);
}
// 输出图像
imagepng($image);
imagedestroy($image);
?>
如何在前端表单中验证用户输入的答案
当用户提交包含验证码输入的表单时,后端需从$_POST中获取用户输入,并与$_SESSION['math_captcha']中存储的答案进行比较。比较时需考虑类型转换,确保数值一致。若匹配成功,则允许继续操作;否则提示错误。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










