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';
}