一個PHP生成的英文驗證碼類

webphp 12年前發布 | 995 次閱讀 Java開發框架 虛擬化

<?php
class verificationCode{

private $image;
private $width;
private $height;
private $pixersum; //干擾點的數目
private $codenum;//驗證字符數目
private $codes;//字符

function __construct($width="100", $height="50", $codenum="4"){
    $this->width=$width;
    $this->height=$height;
    $this->codenum=$codenum;
    $this->codes=$this->strings();
    $this->image=imagecreatetruecolor($this->width, $this->height);
    $this->pixersum=floor($width*$height/50);
}

function showCode(){
    //畫布顏色
    $this->bulidcolor();
    //畫干擾素
    $this->bulidgrs();
    //畫字符
    $this->bulidzifu();
    //輸出并銷毀
    $this->show();
}

function tocode(){
    return $this->codes;
}

private function bulidcolor(){
    //背景顏色
    $red=rand(220, 255);
    $green=rand(220, 255);
    $bule=rand(220, 255);
    $color=imagecolorallocate($this->image, $red, $green, $bule);
    imagefill($this->image, 0, 0, $color);
    //黑色邊框
    imagerectangle($this->image, 0, 0, $this->width-1, $this->height-1, imagecolorallocate($this->image, 0, 0, 0));
}

private function bulidgrs(){

    //畫點
    for($i=0; $i<$this->pixersum; $i++){
        $color=imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));   
        imagesetpixel($this->image, rand(1, $this->width-2), rand(1, $this->height-2), $color);
    }
    //畫弧線
    for($i=0; $i<15; $i++){
        $color=imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
        imagearc($this->image, rand(-10, $this->width), rand(-10, $this->height), rand(10, $this->width), rand(10, $this->height), rand(-30, 30), rand(-30, 30), $color);
    }

}

private function strings(){
    $str="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $strs="";
    for($i=0; $i<$this->codenum; $i++){
        $cha=$str{rand(0, strlen($str))};
        $strs.=$cha;
    }
    return $strs;
}

private function bulidzifu(){
    for($i=0; $i<$this->codenum; $i++){
    $fontcolor=imagecolorallocate($this->image, rand(0, 128), rand(0, 128), rand(0, 128));
    $fontsize=rand(4, 5);
    $x=floor($this->width/$this->codenum)*$i+3;
    $y=rand(0, $this->height-15);
    imagechar($this->image, $fontsize, $x, $y, $this->codes{$i},$fontcolor);
    }

}

private function show(){
    header("Content-Type:image/gif");
    imagegif($this->image);
    imagedestroy($this->image);
}

} ?></pre>

 本文由用戶 webphp 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!