一个高难度问题,关于验证码不显示
本帖最后由 ziluoapo4 于 2014-10-12 17:33:16 编辑 一般验证码不显示,无处乎是因为:1 有bom 头,2 extension=php_gd2.dll没有开启(即去掉分号)
但我这个不是上面这两个原因,因为我都检查了。
论坛里还有解决办法说是在页面中加上开头加上ini_set('display_errors', 'off');我也加也,(见这个帖子:http://bbs.csdn.net/topics/350011289)还是不行,
但说也奇怪,其他的cms程序却显示验证码,我用的php版本是php version 5.3.28
要不我说这是高难度问题呢,这到底是怎么回事呢
------解决思路----------------------
修改了一下,ok了,主要是字体那里,你没有定义root_path,导致获取不到 $this->font = root_path.'/font/elephant.ttf';
把root_path用define方式改为正确路径就可以的,我现在测试目录是这样的。
test.php
font/elephant.ttf
test.php中的root_path设置为 define('root_path', dirname(__file__));
完整测试代码如下:
//验证码类
define('root_path', dirname(__file__));
//验证码类
class validatecode {
private $charset = 'abcdefghkmnprstuvwxyzabcdefghkmnprstuvwxyz23456789'; //随机因子
private $code; //验证码
private $codelen = 4; //验证码长度
private $width = 130; //宽度
private $height = 50; //高度
private $img; //图形资源句柄
private $font; //指定的字体
private $fontsize = 20; //指定字体大小
private $fontcolor; //指定字体颜色
//构造方法初始化
public function __construct() {
$this->font = root_path.'/font/elephant.ttf';
}
//生成随机码
private function createcode() {
$_len = strlen($this->charset)-1;
for ($i=0;$icodelen;$i++) {
$this->code .= $this->charset[mt_rand(0,$_len)];
}
}
//生成背景
private function createbg() {
$this->img = imagecreatetruecolor($this->width, $this->height);
$color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);
}
//生成文字
private function createfont() {
$_x = $this->width / $this->codelen;
for ($i=0;$icodelen;$i++) {
$this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]);
}
}
//生成线条、雪花
private function createline() {
for ($i=0;$i $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
for ($i=0;$i