php教程--案例25-2(验证码生成与验证(线条))

t214.php

<html>
<head>
    <title>验证码生成与验证</title>
    <script type="text/javascript">
        function change1() {
            var change = document.getElementById("change");
            var img = document.getElementById("code_img");
            img.src = "./t215.php?t="+ new Date();
        }
    </script>
</head>
<body>
<form action="./t214.php" method="post">
    <p>用户名:<input type="text" name="user_name" value=""></p>
    <p>密码:<input type="password" name="password" value=""></p>
    <p>验证码:<input type="text" name="captcha"><img id="code_img" src="./t215.php"><a href="#" onclick="change1();">看不清,换一张</a></p>
    <p><input type="submit" name="login" value="登录" style="width: 180px;"></p>

</form>
</body>
</html>


<?php
//case 25-2 验证码生成与验证(线条)

@session_start();
if(isset($_POST['login']))
{
    $code = isset($_POST['captcha'])?trim($_POST['captcha']):'';
    if(!isset($_SESSION['captcha_code'])) die('验证码已过期,请重新登录');
    echo "code=$code"."<br>";
    echo "session =".$_SESSION['captcha_code']."<br>";
    if(strtolower($code) == strtolower($_SESSION['captcha_code']))
    {
        echo "验证码正确";
    }
    else
    {
        echo "验证码输入错误";
    }
    session_destroy();


}

?>

t215.php

<?php
$img_width = 120;
$img_height = 35;
$char_len = 5;
$font = 5;
$char = array_merge(range('A','Z'),range('a','z'),range(1,9));
$rand_keys = array_rand($char,$char_len);
if($char_len == 1)
{
    $rand_keys = array($rand_keys);
}
shuffle($rand_keys);
$code = '';
foreach ($rand_keys as $key)
{
    $code .= $char[$key];
}
@session_start();
$_SESSION['captcha_code'] = $code;

$img = imagecreatetruecolor($img_width,$img_height);
$bg_color = imagecolorallocate($img,0xcc,0xcc,0xcc);
imagefill($img,0,0,$bg_color);
//线条
for ($i=0; $i<=6; $i++)
{
    $color = imagecolorallocate($img,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
    imageline($img,mt_rand(0,$img_width),mt_rand(0,$img_height),mt_rand(0,$img_width),mt_rand(0,$img_height),$color);
}

$rect_color = imagecolorallocate($img,0xff,0xff,0xff);
imagerectangle($img,0,0,$img_width-1,$img_height-1,$rect_color);

$str_color = imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
$font_width = imagefontwidth($font);
$font_height = imagefontheight($font);
$str_width = $font_width * $char_len;
imagestring($img,$font,($img_width-$str_width)/2,($img_height-$font_height)/2,$code,$str_color);
header('Content-type:image/png');
imagepng($img);
imagedestroy($img);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米大王

有你的支持,我会更有动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值