PHP驗證碼不顯示問題

最近遇到登陸頁面中的驗證碼不顯示的問題,查了好多地方纔解決,都快崩潰了。下面說一下解決的方法,其實很簡單。

修改之前的代碼:

<?php
session_start();
Function getRandNumber($fMin,$fMax){
    srand((double)microtime()*1000000);
    $fLen="%0".strlen($fMax)."d ";
    Return sprintf($fLen,rand($fMin,$fMax));
}
$str=getRandNumber(1000,9999);
 
//生成隨機數
//for ($num = 0; $num < 4; $num++) {
//	$str.= dechex(rand(0, 15));//dechex()方法將十進制數轉換爲十六進制
//}
//隨機數轉換爲字符串,並將字符串保存到session
$_SESSION["validateCoder"] = $str + "";//

//生成圖片
$width = 50; //圖片寬度
$height = 18; //圖片高度 
$im=imagecreate($width,$height);

//圖片背景
$_bgR = rand(200, 255);
$_bgG = rand(150, 255);
$_bgB = rand(200, 255);
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
$pix=imagecolorallocate($im,187,230,247);

//文字顏色
$font=imagecolorallocate($im,41,163,238); 
for($i=0;$i<1000;$i++)
{//雪花效果
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);
}
//字符寫在圖像上
@header("Content-Type:image/png");
imagestring($im, rand(0, 50), rand(0, 15), rand(0, 5),$str, $font);
imagerectangle($im,0,0,$width-1,$height-1,$font);
imagepng($im);
imagedestroy($im);
?>
修改之後的代碼:
<?php
@session_start();
Function getRandNumber($fMin,$fMax){
    srand((double)microtime()*1000000);
    $fLen="%0".strlen($fMax)."d ";
    Return sprintf($fLen,rand($fMin,$fMax));
}
$str=getRandNumber(1000,9999);
 
//生成隨機數
//for ($num = 0; $num < 4; $num++) {
//	$str.= dechex(rand(0, 15));//dechex()方法將十進制數轉換爲十六進制
//}
//隨機數轉換爲字符串,並將字符串保存到session
$_SESSION["validateCoder"] = $str + "";//

//生成圖片
$width = 50; //圖片寬度
$height = 18; //圖片高度 
$im=imagecreate($width,$height);

//圖片背景
$_bgR = rand(200, 255);
$_bgG = rand(150, 255);
$_bgB = rand(200, 255);
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
$pix=imagecolorallocate($im,187,230,247);

//文字顏色
$font=imagecolorallocate($im,41,163,238); 
for($i=0;$i<1000;$i++)
{//雪花效果
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);
}
//字符寫在圖像上
@header("Content-Type:image/png");
imagestring($im, rand(0, 50), rand(0, 15), rand(0, 5),$str, $font);
imagerectangle($im,0,0,$width-1,$height-1,$font);
imagepng($im);
imagedestroy($im);
?>
看出有什麼區別了麼?
其實就在session_start()前加了個"@",這樣驗證碼就正常顯示了。

@在PHP中叫錯誤抑制操作符,其作用很簡單,如果@之後的語句執行出錯的話,不在屏幕打印出錯誤信息。如果不用的話錯誤信息就會顯示出來。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章