2012-07-08 65 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(),问题解决了。