匯東網


php 实现验证码确认

[編輯] [转简体]
|
作者:huidong | 分類:【編程】php
[ 42 瀏覽 0 評論 6 贊 6 踩 ]

概要

正文

index.php

<?php
session_start();

if (isset($_REQUEST['authcode']))
{
    if (strtolower($_REQUEST['authcode']) == $_SESSION['captcha_code'])
    {
        echo '<font color ="#0000CC"> 输出正确</font>';
        # code...
    }
    else
    {
        echo $_REQUEST['authcode'];
        echo $_SESSION['authcode'];
        echo '<font color ="#CC0000"> 输出错误</font>';
    }
    exit();
}
?>

<!DOCTYPE html>

<html>
<head>
    <meta charset="gbk" />
    <title>验证码测试</title>
</head>
<body>

    <form method="post">
        <p>
            验证码图片:
            <img id="captcha_img" border="1" src="./captcha_image.php" alt="验证码" />

            <!-- 点击后修改图片链接的随机数参数,迫使图片刷新(否则浏览器会依靠缓存内容而不刷新) -->
            <a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='./captcha_image.php?r=' + Math.random() ">换一个</a>
        </p>

        <p>
            请输入图片中的内容:
            <input type="text" name="authcode" value="" />
        </p>

        <p>
            <input type="submit" value="提交" style="padding: 6px 20px;" />
        </p>

    </form>

</body>
</html>


captcha_image.php

<?php

/**
 * captcha_image.php
 * 每次加载此页面将显示不同的验证码图像,并自动更新 $_SESSION["captcha_code"]
 * 
 * 代码来自:https://blog.csdn.net/chenfang0529/article/details/81295479
 * (huidong 对源码进行了修订和整合)
 *
 * 使用方法:
 *   只需在 HTML 中使用 img 标签展示此页面的图片即可,例如:
 *   <img id="captcha_img" border="1" src="./captcha_image.php" alt="验证码" />
 *   <!-- 点击后修改图片链接的随机数参数,迫使图片刷新(否则浏览器会依靠缓存内容而不刷新)-->
 *   <a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='./captcha_image.php?r=' + Math.random() ">换一个</a>
 * 
 * 创建时间:2024.6.14
 */

session_start();

// 获取随机验证码并存储到 session 中,然后绘制出来
$code = GetRandomCode();
$_SESSION["captcha_code"] = $code;
DrawCaptchaCode($code);

/**** 以下是函数实现 ****/

// 得到随机验证码
// $len 验证码长度
// $data 验证码字典
// 返回值为生成的随机验证码
function GetRandomCode($len = 4, $data = 'abcdefghijkmnpqrstuvwxy3456789')
{
    $code = "";
    for ($i = 0; $i < $len; $i++)
    {
        $code .= substr($data, rand(0, strlen($data) - 1), 1);
    }
    return $code;
}

// 绘制验证码到网页
// 大小:100px * 30px
// $captcha_code 验证码内容
function DrawCaptchaCode($captcha_code)
{
    // 创建 100px * 30px 的画布对象
    $image = imagecreatetruecolor(100, 30);
    
    // 填充背景
    $bgcolor = imagecolorallocate($image, rand(200, 255), rand(200, 255), rand(200, 255));
    imagefill($image, 0, 0, $bgcolor);

    // 绘制文字
    for ($i = 0; $i < strlen($captcha_code); $i++)
    {
        $fontsize = 5;
        $fontcolor = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
        $fontcontent = substr($captcha_code, $i, 1);
        $x = ($i * 100 / 4) + rand(5, 10);
        $y = rand(5, 12);
        imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
    }

    // 噪点
    for ($i = 0; $i < 200; $i++)
    {
        // 选取随机颜色
        $pointcolor = imagecolorallocate($image, rand(50, 200), rand(50, 200), rand(50, 200));
        
        // 绘制随机噪点
        imagesetpixel($image, rand(1, 99), rand(1, 29), $pointcolor);
    }

    // 干扰线
    for ($i = 0; $i < 5; $i++)
    {
        // 选取随机颜色
        $linecolor = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
        
        // 绘制随机直线
        imageline($image, rand(1, 99), rand(1, 29), rand(1, 99), rand(1, 29), $linecolor);
    }

    // 输出图像文件
    header('content-type:image/png');
    imagepng($image);

    // 销毁画布对象
    imagedestroy($image);
}

?>



js 版本,做个记录。代码来自网络,使用 canvas 绘制。(原博客链接已丢失)

<!DOCTYPE html>
<html>
<!-- head -->
<head>
  <title>图片登录验证</title>
</head>
<body>
     <input type="text" value="" placeholder="请输入验证码(区分大小写)" 
     style="height:43px;position: relative; top:-15px; font-size:20px;"id ="text">
     <canvas id="canvas" width="100" height="43" onclick="dj()" 
      style="border: 1px solid #ccc;
        border-radius: 5px;"></canvas>
     <button class="btn" onclick="sublim()">提交</button>
    </body>
    
<script>
    var show_num = [];
    draw(show_num);
    
    function dj()
    {
        draw(show_num);   
    }
    
    function sublim()
    {
        var val=document.getElementById("text").value;  
        var num = show_num.join("");
        if(val=='')
        {
            alert('请输入验证码!');
        }
        else if(val == num)
        {
            alert('提交成功!');
            document.getElementById(".input-val").val('');
            draw(show_num);

        }
        else
        {
            alert('验证码错误!\n你输入的是:  '+val+"\n正确的是:  "+num+'\n请重新输入!');
            document.getElementById("text").value='';
            draw(show_num);
        }
    }
    
    function draw(show_num)
    {
        var canvas_width=document.getElementById('canvas').clientWidth;
        var canvas_height=document.getElementById('canvas').clientHeight;
        var canvas = document.getElementById("canvas");//获取到canvas的对象,演员
        var context = canvas.getContext("2d");//获取到canvas画图的环境,演员表演的舞台
        canvas.width = canvas_width;
        canvas.height = canvas_height;
        var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
        var aCode = sCode.split(",");
        var aLength = aCode.length;//获取到数组的长度

        for (var i = 0; i <= 3; i++)
        {
            var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
            var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
            var txt = aCode[j];//得到随机的一个内容
            show_num[i] = txt;
            var x = 10 + i * 20;//文字在canvas上的x坐标
            var y = 20 + Math.random() * 8;//文字在canvas上的y坐标
            context.font = "bold 23px 微软雅黑";

            context.translate(x, y);
            context.rotate(deg);

            context.fillStyle = randomColor();
            context.fillText(txt, 0, 0);

            context.rotate(-deg);
            context.translate(-x, -y);
        }
        
        // 验证码上显示线条
        for (var i = 0; i <= 5; i++)
        {
            context.strokeStyle = randomColor();
            context.beginPath();
            context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
            context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
            context.stroke();
        }
        // 验证码上显示小点
        for (var i = 0; i <= 30; i++)
        {
            context.strokeStyle = randomColor();
            context.beginPath();
            var x = Math.random() * canvas_width;
            var y = Math.random() * canvas_height;
            context.moveTo(x, y);
            context.lineTo(x + 1, y + 1);
            context.stroke();
        }
    }
    
    // 得到随机的颜色值
    function randomColor()
    {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
    }
    
</script>
    
    
</html>


[ 6] [ 6]


 評論區  0 條評論

+ 添加評論