我的第一个PHP 自定义函数:验证码生成


 

 

/**

*_nmsg()生成验证码
*@access public
*@param int $_width 验证码宽度
*@param int $_height 验证码高度
*@param int $_rnd_count 验证码位数
*@param bool $_rnd_count 验证码边框
*return void
*/

function _nmsg($_width=75,$_height = 25,$_rnd_count=4,$_flag=true){

//产生随机数
    session_start();
    for($i=0;$i<$_rnd_count;$i++){
        @$_nmsg.=dechex(mt_rand(0,15));
    }
    $_SESSION['nmsg']=$_nmsg;

    //创建图像
    header("Content-Type:image/png");
    $_img=imagecreatetruecolor($_width,$_height);

    //背景颜色(白色)
    $_white=imagecolorallocate($_img,255,255,255);

    //填充颜色
    imagefill($_img,0,0,$_white);

    //边框颜色(黑色)
    $_black=imagecolorallocate($_img,0,0,0);

    //边框开关
    if($_flag){
    //创建边框
    imagerectangle($_img,0,0,$_width-1,$_height-1,$_black);
    }

    //随机线条生成
    for($i=0;$i<6;$i++){
        $_rnd_color=imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
        imageline($_img,mt_rand(2,$_width-2),mt_rand(2,$_height-2),mt_rand(2,$_width-2),mt_rand(2,$_height-2),$_rnd_color);
    }

    //随机雪花
    for($i=0;$i<100;$i++){
        $_rnd_color=imagecolorallocate($_img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
        imagestring($_img,1,mt_rand(1,$_width-7),mt_rand(1,$_height-7),'*',$_rnd_color);
    }

    //输出验证码
    for($i=0;$i<$_rnd_count;$i++){
        $_rnd_color=imagecolorallocate($_img,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
        imagestring($_img,mt_rand(3,5),$i*$_width/$_rnd_count+mt_rand(1,10),mt_rand(1,$_height/2),$_SESSION['nmsg'][$i],$_rnd_color);    
    }


    //输出图像
    imagepng($_img);

    //销毁图像
    imagedestroy($_img);
}

js刷新部分

window.onload=function(){
    var nmsg = document.getElementById('nmsg');
    nmsg.onclick=function(){
        nmsg.src='code.php?tm='+Math.random();
    };
}

 

posted @ 2015-09-17 15:18  Swordsking  阅读(222)  评论(0编辑  收藏  举报