php实现图片加法验证码

php 复制代码
<?php
/**
 * Created by PhpStorm.
 * User: finejade
 * Date: 2023-10-19
 * Time: 11:07
 */
session_start(); // 启动Session
require_once('common.php');
session_start();
/*定义头文件为图片*/
header("Content-type: image/png");
/*生成验证码*/
/*创建图片设置字体颜色*/
$w = 70;
$h = 25;
$im = imagecreate($w, $h);
$red = imagecolorallocate($im, 255, 255, 255);
$white = imagecolorallocate($im, 255, 255, 255);
/*随机生成两个数字*/
$num1 = rand(1, 20);
$num2 = rand(1, 20);
$_SESSION ["captcha"] = $num1 + $num2;
/*设置图片背景颜色*/
$gray = imagecolorallocate($im, 118, 151, 199);
$black = imagecolorallocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100));
/*创建图片背景*/
imagefilledrectangle($im, 0, 0, 100, 24, $black);
/*在画布上随机生成大量点*/
for ($i = 0; $i < 80; $i++) {
    imagesetpixel($im, rand(0, $w), rand(0, $h), $gray);
}
/*将计算验证码写入到图片中*/
imagestring($im, 5, 5, 4, $num1, $red);
imagestring($im, 5, 30, 3, "+", $red);
imagestring($im, 5, 45, 4, $num2, $red);
imagestring($im, 5, 70, 3, "=", $red);
imagestring($im, 5, 80, 2, "?", $white);
/*输出图片*/
imagepng($im);
imagedestroy($im);

代码中校验

php 复制代码
	session_start();
    $captcha = isset($_POST['captcha']) ? $_POST['captcha'] : '';
     if ($_SESSION ["captcha"] != $captcha) {
            return error('图形验证码不正确');
        }

前端代码

html 复制代码
<img src="captcha.php" width="70" height="30"  id="valid-img" title="点击再换一张" class="vail_img" alt="验证码图片"/>
js 复制代码
    $("#valid-img").click(function () {
        $(this)[0].src ='captcha.php?'+Math.random();
    })
相关推荐
APIshop24 分钟前
实战解析:苏宁易购 item_search 按关键字搜索商品API接口
开发语言·chrome·python
百***920227 分钟前
java进阶1——JVM
java·开发语言·jvm
蓝桉~MLGT34 分钟前
Python学习历程——Python面向对象编程详解
开发语言·python·学习
Evand J36 分钟前
【MATLAB例程】2雷达二维目标跟踪滤波系统-UKF(无迹卡尔曼滤波)实现,目标匀速运动模型(带扰动)。附代码下载链接
开发语言·matlab·目标跟踪·滤波·卡尔曼滤波
larance39 分钟前
Python 中的 *args 和 **kwargs
开发语言·python
Easonmax42 分钟前
用 Rust 打造可复现的 ASCII 艺术渲染器:从像素到字符的完整工程实践
开发语言·后端·rust
lsx2024061 小时前
Rust 宏:深入理解与高效使用
开发语言
百锦再1 小时前
选择Rust的理由:从内存管理到抛弃抽象
android·java·开发语言·后端·python·rust·go
小羊失眠啦.1 小时前
深入解析Rust的所有权系统:告别空指针和数据竞争
开发语言·后端·rust
Dxxyyyy1 小时前
零基础学JAVA--Day32(ArrayList底层+Vector+LinkedList)
java·开发语言