php生成驗證碼

2022-08-31 21:09:12 字數 1552 閱讀 4103

由於最近乙個專案需要,需要做驗證碼,本想偷懶直接用tp框架裡面的,但是感覺很醜陋,而且調整大小後字串在中的位置不是很美觀.所以自己寫了乙個驗證碼.考慮到讓以後也能用到, 所以要保證不同字元,不同高寬的情況下字元顯示均勻.

由於使用imagesting寫入字串調整字型大小有點問題,而且字型過於單一,這裡我採用了gd庫中的imagettftext函式,此函式用法不再贅述,但是有乙個引數一開始沒有理解,造成了很大的困擾.

imagettftext( resource image, float size, float angle,

int x, int y, int color, string fontfile, string text )

第五個引數y,一開始認為是字型與頂部的距離.但是測試之後發現是字型底部與頂部之間的距離,所以在這裡要使中的字串垂直居中就必須滿足y=(高度 +字型高度)/2.另外驗證碼中,對字串位置起重要作用的屬性包括:高度, 寬度,字串個數,字型大小,繪製字型起始座標.

實現**:

class captcha

} else

}if(!isset($this->height))//高度

if(!isset($this->ttf))//字型

$this->string = explode(",",$this->string);//將字串集合轉為陣列

//生成

$this->createimg();

$this->printstr($num);

$this->printline();

$this->printpoint(); }

public function display()//輸出影象

/***********************************/

private function createimg()//建立影象

else

}private function printstr($len)//輸出字串 }

private function printline()//輸出干擾線條

else

$this->linenum--;

}} }

private function printpoint()//輸出干擾點

} }

private function getrandcolor()//取隨機顏色

private function getrand($arr)//取隨機數

}

呼叫**:

$a = new captcha();

$a->ttf = "comic.ttf";

$a->linenum = 10;

$a->pointnum = 50;

$a->printimg(4);

$a->display();

這裡使用了字型檔案,如果需要測試,還請包含這個檔案.

最終效果圖:

php生成驗證碼

header content type image gif 初始化 border 0 是否要邊框 1要 0不要 how 4 驗證碼位數 w how 15 寬度 h 20 高度 fontsize 5 字型大小 alpha abcdefghijkmnopqrstuvwxyz 驗證碼內容1 字母 numb...

php 生成驗證碼

驗證碼個數 num 4 驗證碼寬度 width 80 驗證碼高度 height 20 驗證碼 注意是字串 code 生成驗證碼 for i 0 i num i 驗證碼儲存到session中 session start session verifycode code 建立影象 image imagec...

php 生成驗證碼

che.php session start im imagecreatetruecolor 100,30 設定顏色 bg imagecolorallocate im,0,0,0 背景色 te imagecolorallocate im,255,255,255 字型顏色 for i 0 i 4 i 輸...