给大家提供一个验证码方法

浏览:487 发布日期:2017/08/23 分类:技术分享
上次不知道在哪儿看到的这种验证码,自己搞了一个出来function getCode ($len=5,$width=200,$height=40) {
    header("Content-type: image/PNG");
    $dbfile = dirname(__FILE__)."/strDb.txt";
    $str = trim(file_get_contents($dbfile));
    $strdb = str_split($str,3);
    $suijiwei = mt_rand(0,$len-1);//产生一个与众不同的数字位
    session("position",$suijiwei);
    $fontfile = dirname(__FILE__)."/pomoti.ttf";
    $image = imagecreatetruecolor($width, $height);
    $bgcolor = imagecolorallocate($image, 255,255,255);
    imagefill($image,0,0,$bgcolor);
    //雪花
    for ($i=0;$i<100;$i++) {
        $color = imagecolorallocate($image,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
        imagestring($image,mt_rand(1,5),mt_rand(0,$width),mt_rand(0,$height),'.',$color);
    }
    //产生随机数
    for($i=0; $i<$len; $i++) {
        $fontcolor = imagecolorallocate($image, 100, 100, 100);
        $cn = $strdb[rand(0,count($strdb)-1)];
        $dushu = $i== $suijiwei?180:0;
        $x =  $i== $suijiwei?($width/$len)*$i + ($width/$len)-7:($width/$len)*$i+7;
        $y =   $i== $suijiwei?$height -($height-10):$height-10;
        imagettftext($image, $height/2,$dushu,$x ,$y,$fontcolor, $fontfile, $cn);
    }
    ImagePNG($image);
    ImageDestroy($image);
}
调用方法就是:
在模板就:<img src="{:getCode(5)}">
在控制器里就: return getCode(5);
最佳答案
评论( 相关
后面还有条评论,点击查看>>