php教程--案例25-2(验证码生成与验证(线条))
发布日期:2021-05-06 21:10:29 浏览次数:16 分类:原创文章

本文共 2354 字,大约阅读时间需要 7 分钟。

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);

 

上一篇:php教程--案例26(文件管理器)
下一篇:php教程--案例25(验证码生成与验证)

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年03月22日 06时08分31秒