//驗證碼類
class ValidateCode {
private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; //隨機因子
private $code; //驗證碼
private $codelen = 4; //驗證碼長度
private $width = 130; //寬度
private $height = 50; //高度
private $img; //圖形資源控制代碼
private $font; //指定的字型
private $fontsize = 20; //指定字型大小
private $fontcolor; //指定字型顏色
//構造方法初始化
public function __construct() {
$this->font = ROOT_PATH.'/font/elephant.ttf';
}
//產生隨機碼
private function createCode() {
$_len = strlen($this->charset)-1;
for ($i=0;$i<$this->codelen;$i++) {
$this->code .= $this->charset[mt_rand(0,$_len)];
}
}
//產生背景
private function createBg() {
$this->img = imagecreatetruecolor($this->width, $this->height);
$color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);
}
//產生文字
private function createFont() {
$_x = $this->width / $this->codelen;
for ($i=0;$i<$this->codelen;$i++) {
$this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]);
}
}
//產生線條、雪花
private function createLine() {
for ($i=0;$i<6;$i++) {
$color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
for ($i=0;$i<100;$i++) {
$color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
}
}
//輸出
private function outPut() {
header('Content-type:image/png');
imagepng($this->img);
imagedestroy($this->img);
}
//對外產生
public function doimg() {
$this->createBg();
$this->createCode();
$this->createLine();
$this->createFont();
$this->outPut();
}
//擷取驗證碼
public function getCode() {
return strtolower($this->code);
}
}
?>
單獨建一個檔案顯示是正常的,放到mvc模式下的方法中顯示圖片就xx了。
正常的:
define('ROOT_PATH', dirname(__FILE__));
require './core/ValidateCode.class.php'; //先把類包含進來,實際路徑根據實際情況進行修改。
$_vc = new ValidateCode(); //執行個體化一個對象
$_vc->doimg();
$_SESSION['code'] = $_vc->getCode();//驗證碼儲存到SESSION中
?>
顯示x的:
class UsersController extends Controller {
public function login(){
$this->smarty->display( 'login.html' );
}
public function verifi(){
$_vc = new ValidateCode(); //執行個體化一個對象
$_vc->doimg();
//$_SESSION['code'] = $_vc->getCode();//驗證碼儲存到SESSION中
}
}
?>
回複討論(解決方案)
代碼一樣的話,檢查一下BOM頭。
代碼一樣的話,檢查一下BOM頭。
檢查過了,沒bom
代碼一樣的話,檢查一下BOM頭。
檢查過了,沒bom
不要直接輸出圖片,檢查是否有錯誤。header()那一部分先注釋掉,看報錯。