生成动态验证码

php代码

<?php
    header('Content-Type:image/png');//设置content-type为png图片
    header('Cache-Control:no-cache');//设置为不能缓存
    //设置验证码的宽高
    $w = 120;
    $h = 40;

    //要在服务器内存中创建一个图片
    $img = imagecreate($w,$h);

    //为图片分配一个背景颜色,RGB(255,255,255)
    //2,3,4参数代表RGB,之所以分配180和240,是为了生成一个浅色的背景
    imagecolorallocate($img,rand(180,240),rand(180,240),rand(180,240));

    //在图片上生成随机字符
    $src = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    //想要生成4位的验证码
    for($i=0;$i<4;$i++){
    //生成一个1位的从1-36之间的随机数字
        $c = $src[rand(1,strlen($src))-1];
        $color = imagecolorallocate($img,rand(50,170),rand(50,170),rand(50,170));
        imagestring($img,10,20+$i*20,10,$c,$color);
    }
    imagepng($img);
    imagedestroy($img);
?>

js代码

<script>
        $(function(){
            $("#btn").click(function(){
                $('img').attr("src",'yzm.php?' + Math.random());
            });
        })
    </script>
原文地址:https://www.cnblogs.com/liyuhuan/p/5502358.html