1、新建一个html文件把下面代码复制进去

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>验证码验证</title>
</head>
<body>

<form id="verifyForm">
    <label for="verifyCode">请输入验证码:</label>
    <input type="text" id="verifyCodeInput" name="verifyCode">
    <img id="verifyImage" src="generate_captcha.php" alt="验证码">
    <button type="button" onclick="verifyCaptcha()">验证</button>
</form>

<script>
function verifyCaptcha() {
    var userInput = document.getElementById('verifyCodeInput').value;

    // 发送验证码验证请求
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'verify_captcha.php', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var response = xhr.responseText;
            if (response == 'success') {
                alert('验证码验证成功!');
            } else {
                alert('验证码验证失败!');
                document.getElementById('verifyImage').src = 'generate_captcha.php?' + Math.random(); // 刷新验证码图片
            }
        }
    };
    xhr.send('verifyCode=' + userInput);
}
</script>

</body>
</html>

2、新建 verify_captcha.php 文件把以下代码复制进去

<?php
session_start();

$verifyCode = $_SESSION['verifycode'];
$userInput = $_POST['verifyCode'];

if ($verifyCode == $userInput) {
    echo 'success';
} else {
    echo 'fail';
}
?>

3、新建 generate_captcha.php 将下面二维码api代码放进去就行了

<?php
##生成验证码文件

session_start();

header("Content-type: image/png");
##生成验证码图片

$str = "1,2,3,4,5,6,7,8,9,0,q,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";      
##要显示的字符,可自己进行增删

$list = explode(",", $str);
$cmax = count($list) - 1;
$verifyCode = '';
for ( $i=0; $i < 4; $i++ ){
    $randnum = mt_rand(0, $cmax);
    $verifyCode .= $list[$randnum];                  
    ##取出字符,组合成为我们要的验证码字符
}
$_SESSION['verifycode'] = $verifyCode;        
##将字符放入SESSION中

$im = imagecreate(50,20);    
##生成图片

$black = imagecolorallocate($im, 0,0,0);
$white = imagecolorallocate($im, 255,255,255);
$green = imagecolorallocate($im, 0,190,0);
$gray = imagecolorallocate($im, 180,200,200);
$red = imagecolorallocate($im, 190, 0, 0);
##设置的颜色

imagefill($im,0,0,$white);     
##给图片填充颜色

imagestring($im, 5, 8, 2, $verifyCode, $black);   
##将验证码写入到图片中

for($i=0;$i<20;$i++) {
    imagesetpixel($im, rand(0,48), rand(0,18), $green);    
    imagesetpixel($im, rand(0,48), rand(0,18), $red);
    imagesetpixel($im, rand(0,48), rand(0,18), $gray);
}
##加入点状干扰象素

imagepng($im);
imagedestroy($im);
?>

原文地址