php生成并处理图片验证码

本文介绍了如何使用PHP的captcha库通过composer安装,并提供了四个使用案例:1) 生成并输出验证码;2) 保存验证码信息到session;3) 刷新页面验证码;4) 异步验证输入内容。涉及前后端交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

php使用captcha生成验证码,其composer地址如下

https://packagist.org/packages/gregwar/captcha

composer安装captcha

composer require gregwar/captcha

使用案例1:生成并输出验证码

<?php

// 自动加载
require 'vendor/autoload.php';
// 设置输出格式为jpeg
header('Content-type: image/jpeg');
use Gregwar\Captcha\CaptchaBuilder;
// 生成并输出验证码
$builder = new CaptchaBuilder;
$builder->build();
$builder->output();

使用案例2:生成验证码并将验证码信息保存到session中

<?php
// 开启session
session_start();
header('Content-type: image/jpeg');
require 'vendor/autoload.php';
use Gregwar\Captcha\CaptchaBuilder;

$builder = new CaptchaBuilder;
$builder->build();
// 将验证码内容存入session中
$_SESSION['captcha'] = $builder->getPhrase();
$builder->output();

使用案例3:在页面中刷新验证码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<img id="captcha" src="http://192.168.0.131/composer/captcha.php" >
		<button id="shuaxin" type="button">刷新</button>
		<script type="text/javascript">
			document.getElementById('shuaxin').addEventListener('click',function () {
			   var captcha = document.getElementById("captcha");
			   captcha.src="http://192.168.0.131/composer/captcha.php?"+Math.random();
			})
		</script>
	</body>
</html>

使用案例4:异步验证输入内容

前端

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>验证码</title>
		<script src="../js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<input id="content" type="text" name="captcha" id="" value="" />
		<img id="captcha" src="http://192.168.0.131/composer/captcha.php">
		<button id="shuaxin" type="button">刷新</button>
		<script type="text/javascript">
			document.getElementById('shuaxin').addEventListener('click', function() {
				var captcha = document.getElementById("captcha");
				captcha.src = "http://192.168.0.131/composer/captcha.php?" + Math.random();
			})
			// 输入框的失焦监听事件
			document.getElementById('content').addEventListener('blur', function() {
				// 获取输入框的内容
				var captcha = document.getElementById("content").value;
				// 异步验证输入信息
				$.ajax({
					url: "http://192.168.0.131/composer/yzm.php?captcha=" + captcha,
					success: function(result) {
						if (result == 1) {
							alert('验证成功');
						} else {
							alert('验证失败,请重新输入');
						}
					}
				});
			})
		</script>
	</body>
</html>

后端

<?php
// 开启session
session_start();
// GET形式获取前端的输入信息
$captcha = $_GET['captcha'];
// 验证输入的内容是否正确
if( $captcha == $_SESSION['captcha']){
	echo '1';
}else{
	echo '0';
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值