如果在类文件之外创建实例,验证码类不会显示图像


captcha class wont display image if an instance is made outside of class file

我创建了一个captcha类来生成验证码。由于某种原因,如果我在类文件本身中创建类的实例,我只能显示图像。否则我什么也得不到。在firebug中,我看到文件被包含,但它被发送为html,尽管我使用header("Content-type: image/png");
class.captcha.php

<?php
class captcha
{
    public $length=4;
    public $width=150;
    public $height=50;
    public $allowedChar='1234569ACEFGHJKMNPQRSTXZ';
    public $font='Arcade.ttf';
    public $fontSize=25;
    public $fontRed=0;
    public $fontGreen=0;
    public $fontBlue=104;
    public $backgroundRed=204;
    public $backgroundGreen=204;
    public $backgroundBlue=255;
    public $noiseRed=0;
    public $noiseGreen=0;
    public $noiseBlue=104;
    public $noisePercent=5;
    /*
    ** @RETURN IMAGE raw image of captcha
    */
    public function create($name)
    {
        //string
        for ($i=0;$i<$this->length;$i++) 
        {$captcha.= $this->allowedChar[mt_rand(0, strlen($this->allowedChar))];}
        //image
        $img=imagecreatetruecolor($this->width, $this->height);
        //colors
        $bgColor=imagecolorallocate($img, $this->backgroundRed, $this->backgroundGreen, $this->backgroundBlue);
        $fontColor=imagecolorallocate($img, $this->fontRed, $this->fontGreen, $this->fontBlue);
        $noiseColor=imagecolorallocate($img, $this->noiseRed, $this->noiseGreen, $this->noiseBlue);
        imagefilledrectangle($img,0,0,$this->width+1,$this->height+1,$bgColor);
        //text
        for($i=0;$i<strlen($captcha);$i++)
        {
            $rotate=rand(0, 80)-40;
            $offX=$i*$this->fontSize+rand($this->fontSize, $this->fontSize*1.2);
            $offY=$this->fontSize+rand($this->fontSize/2, $this->fontSize);;
            $letter=$captcha[$i];
            imagettftext($img, $this->fontSize, $rotate, $offX, $offY, $fontColor, $this->font, $letter);
        }
        //add noise
        for($i=0;$i<$this->height*$this->width*($this->noisePercent/100);$i++)
        {
            //noise
            $x=rand(0, $this->width);
            $y=rand(0, $this->height);
            imagesetpixel($img, $x, $y, $noiseColor);
        }
        $_SESSION[$name]=md5($captcha);
        return $img;
    }
}
?>


captcha.contact.php

<?php
session_start(); 
include('class.captcha.php');
$c=new captcha;
header("Content-type: image/png"); 
imagepng($c->create('contactCaptcha'));
?>

链接到上面,如果它有帮助http://yamikowebs.com/_test/_php/class.captcha.php错误是The image “http://yamikowebs.com/_test/_php/captcha.contact.php” cannot be displayed because it contains errors.
如果我把capture.contact.php的内容放在class. capcha .php的末尾,它就可以正常工作了

我认为解决方案可能是你正在使用PHP的结束标签:

?>

它们不是必需的,但有时是有害的。如果在这样的标记之后有任何标志,您试图发送的头将不会被发送,并且可能出现通知(取决于error_reporting设置)。

只要删除关闭标签(?>),这应该是好的。

另外一件事-如果脚本需要某些东西(例如您的类文件)才能工作,请使用require()而不是include()

contact.captcha.php

<?php
include('class.captcha.php');
$c=new captcha;
header("Content-type: image/png"); 
imagepng($c->create('contactCaptcha'));
?>

session_start()发送头信息,所以一旦删除它就开始工作了