日期:2014-05-17  浏览次数:20394 次

验证码乱码问题
我写了一个验证码类,为了大家帮忙找错误,我把类的代码贴出来,编码格式gbk

<?php
header ("Content-type: image/png; charset=gbk");
class CheckCode {
private $mCheckCodeNum = 4;
private $mCheckCode = '';
private $mCheckImage = '';
private $mDisturbColor = '';
private $mCheckImageWidth = '80';
private $mCheckImageHeight = '20';
public function CreateCheckCode()
{
  $this->mCheckCode = strtoupper(substr(md5(rand()),0,$this->mCheckCodeNum));
  return $this->mCheckCode;
}

private function CreateImage()
{
  $this->mCheckImage = @imagecreate ($this->mCheckImageWidth,$this->mCheckImageHeight);
  imagecolorallocate ($this->mCheckImage, 200, 200, 200);
  return $this->mCheckImage;
}

private function SetDisturbColor()
{
  for ($i=0;$i<=128;$i++)
  {
  $this->mDisturbColor = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,255), rand(0,255));
  imagesetpixel($this->mCheckImage,rand(2,128),rand(2,38),$this->mDisturbColor);
  }
}

public function SetCheckImageWH($width,$height)
{
  if($width==''||$height=='')return false;
  $this->mCheckImageWidth = $width;
  $this->mCheckImageHeight = $height;
  return true;
}

private function WriteCheckCodeToImage()
{
  for ($i=0;$i<=$this->mCheckCodeNum;$i++)
  {
  $bg_color = imagecolorallocate ($this->mCheckImage, rand(0,255), rand(0,128), rand(0,255));
  $x = floor($this->mCheckImageWidth/$this->mCheckCodeNum)*$i;
  $y = rand(0,$this->mCheckImageHeight-15);
  imagechar ($this->mCheckImage, 5, $x, $y, $this->mCheckCode[$i], $bg_color);
  }
}

public function OutCheckImage()
{
  $this ->CreateCheckCode();
  $this ->CreateImage();
  $this ->SetDisturbColor();
  $this ->WriteCheckCodeToImage();
  imagepng($this->mCheckImage);
  imagedestroy($this->mCheckImage);
}
}
?>

在此页面内 定义输出
$c_check_code_image = new CheckCode();
$c_check_code_image ->OutCheckImage();
都完全正常,正常显示一个验证码
但是我新建一个PHP页面,把include这个类之后,放上上面两句代码就出现乱码了,错误代码提示Warning: Cannot modify header information - headers already sent by (output started at E:\www\HSreport\check_code.php:1) in E:\www\HSreport\class\CheckCode.class.php on line 2
塒NG  IHDRP- J?昉LTE热揉С榁番l分?栖涡簐?$趕峣芧哻8哅焲m'?y?6e 4€?5&"?"螛浿劮H肫责╗Xw`[?"?*岝#釵擝錕沇 7坯D窈??鴧^I%篥M8?A峾?>'祋摢??I8ovO?WiAg&攂丬 ub釂U?嵤]迭嬙讣&,,A|t?,笞[敱? ?初o缽C俁?4EG鞽哮|繸爐LL驆h!倪?.?>e?)€埳3塝?醄McQ€濖鉎h幝-/儎?-x酟茴?殶揃"uE^?qJR%? G尗?xu/脥T駊佘a踎,7-<嘽墦超?聻? 蓲遥jY l.D1/噥?.剼囃@T鱝O6( ?#檱臔4箐pG ? 洜葵0@~i捦?貝?&?<v ?$6? 蓅 葽?曤DK鼈So〧ɑIEND瓸`
放到登录页面也是一样,请教,救命啊

------解决方案--------------------
应该是你新建的那个调用页面有BOM头,总之在header()之前有输出了
解决方法
------解决方案--------------------
检查各个页面编码是否同一,还有就是header()之前是否有输出语句!