2012-07-08 68 views
0

我有以下用於顯示網頁中驗證碼的php腳本,captcha在我本地的apache服務器中正確顯示,但是當我上傳到虛擬主機服務器時,出現如下所述的錯誤,請幫助在PHP中顯示驗證碼時出現錯誤

<?php 
session_start(); 

$str = ""; 
$length = 0; 
for ($i = 0; $i < 6; $i++) { 
    // these numbers represent ASCII table (small letters) 
    $str .= chr(rand(97, 122)); 
} 

//md5 letters and saving them to session 
$letters = md5($str); 
$_SESSION['letters'] = $letters; 

//determine width and height for our image and create it 
$imgW = 150; 
$imgH = 50; 
$image = imagecreatetruecolor($imgW, $imgH); 

//setup background color and border color 
$backgr_col = imagecolorallocate($image, 238,239,239); 
$border_col = imagecolorallocate($image, 208,208,208); 

//let's choose color in range of purple color 
$text_col = imagecolorallocate($image, rand(70,90),rand(50,70),rand(120,140)); 

//now fill rectangle and draw border 
imagefilledrectangle($image, 0, 0, $imgW, $imgH, $backgr_col); 
imagerectangle($image, 0, 0, $imgW-1, $imgH-1, $border_col); 

//save fonts in same folder where you PHP captcha script is 
//name these fonts by numbers from 1 to 3 
//we shall choose different font each time 
$fn = rand(1,3); 
$font = $fn . ".ttf"; 

//setup captcha letter size and angle of captcha letters 
$font_size = $imgH/2.0; 
$angle = rand(-15,15); 
$box = imagettfbbox($font_size, $angle, $font, $str); 
$x = (int)($imgW - $box[4])/2; 
$y = (int)($imgH - $box[5])/2; 
imagettftext($image, $font_size, $angle, $x, $y, $text_col, $font, $str); 

//now we should output captcha image 
header("Content-type: image/png"); 
imagepng($image); 
imagedestroy ($image); 
?> 

和錯誤是

Error: Image corrupt or truncated: http://url/captcha.php 
Source File: http://url/captcha.php 
+1

刪除結尾'?>'標記,確保錯誤記錄已打開,請檢查錯誤日誌。 – DCoder 2012-07-08 05:36:39

+0

嘗試添加'error_reporting(E_ALL); ini_set('display_errors',1);'在'session_start()'之前的腳本開頭,然後註釋掉'header('Content-Type:image/png');'line並嘗試加載瀏覽器。你應該看到來自PHP的一些錯誤消息來解釋這個問題。最好的猜測是FreeType(ttf函數)沒有安裝。 – drew010 2012-07-10 00:21:54

回答

5

我有一個問題,即使用CAPTCHA(與imagepng())一臺機器上工作,但不是在遠程服務器上。我使用十六進制編輯器檢查了PNG文件,並在前4個字節中找到了額外的0D0A。我在imagepng()之前調用了ob_clean(),問題解決了。