制作验证码

来源:互联网 发布:汤姆汉克斯的地位知乎 编辑:程序博客网 时间:2024/06/05 06:17

制作验证码文件

<?php    generate_code();    //生成验证码    function generate_code($w = 100, $h = 40, $n = 4) {        $im = imagecreatetruecolor(100, 40);        //背景颜色        $color = imagecolorallocate($im, rand(224, 255), rand(224, 255), rand(224, 255));        imagefill($im, 0, 0, $color);        for($i = 0; $i < $n * 10; $i++) {            //干扰点            $color = imagecolorallocate($im, rand(0, 207), rand(0, 207), rand(0, 207));            $px = rand(0, $w - 1);            $py = rand(0, $h - 1);            imagesetpixel($im, $px, $py, $color);            //干扰线            if($i % 10 == 0) {                $color = imagecolorallocate($im, rand(0, 207), rand(0, 207), rand(0, 207));                $x1 = rand(0, $w - 1);                $y1 = rand(0, $h - 1);                $x2 = rand(0, $w - 1);                $y2 = rand(0, $h - 1);                imageline($im, $x1, $y1, $x2, $y2, $color);            }        }        $str = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz123456789";        $code = ""; //验证码        $fontsize = ceil(($w - 20) / $n);        for($i = 0; $i < $n; $i++) {            $color = imagecolorallocate($im, rand(0, 207), rand(0, 207), rand(0, 207));            $x = 10 + $fontsize * $i;            $y = $h / 2 + $fontsize / 2;            $index = rand(0, strlen($str) - 1);            $ch = $str[$index];            imagettftext($im, $fontsize, rand(-30, 30), $x, $y, $color, "fonts/Arial.ttf", $ch);            $code .= $ch;        }        header("content-type:image/png");        imagepng($im);        imagedestroy($im);        //如果没有开启SESSION 开启SESSION        if(!isset($_SESSION)) {            session_start();        }        $_SESSION["code"] = $code;    }?>
输入验证码

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>输入验证码</title></head><body>    <form action="inputcode.php" method="post">        请输入验证码        <input type="text" name="ecode">        <img id="ecode-img" src="code.php">        <input type="submit" value="提交">    </form></body><script type="text/javascript" src="inputcode.js"></script><?php    check_code();    function check_code() {        if(!isset($_POST["ecode"])) {            return;        }        //如果没有开启SESSION 开启SESSION        if(!isset($_SESSION)) {            session_start();        }        //不区分大小写        if(strtolower($_POST["ecode"]) == strtolower($_SESSION["code"])) {            echo "<script>alert('验证码正确');</script>";        } else {            echo "<script>alert('验证码错误');</script>";        }    }?></html>
JavaScript

varecodeImg= document.getElementById("ecode-img");

//点击时换一张验证码ecodeImg.onclick = function() {    this.src = "code.php?" + Math.random();}

0 0
原创粉丝点击