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

PHP 输出session 验证码与图片不同步,图片总是快一步,求解!
本帖最后由 Xdawei 于 2012-04-18 20:07:42 编辑
PHP 输出session 验证码与图片不同步,图片总是快一步,求解!


<?
session_start();
function random($len)
{
$srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
mt_srand();
$strs="";
for($i=0;$i<$len;$i++){
$strs.=$srcstr[mt_rand(0,35)];
}
return strtoupper($strs);
}
$str=random(4); 
$width = 50; 
$height = 25; 
@header("Content-Type:image/png");
$_SESSION["captcha"] = $str;
//echo $str;
$im=imagecreate($width,$height);
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);
$pix=imagecolorallocate($im,187,230,247);
$font=imagecolorallocate($im,41,163,238);
mt_srand();
for($i=0;$i<1000;$i++)
{
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);
}
imagestring($im, 5, 7, 5,$str, $font);
imagerectangle($im,0,0,$width-1,$height-1,$font);
imagepng($im);
imagedestroy($im);
$_SESSION["captcha"] = $str;
?>




<img src="captcha.php" width="60" height="22" border="1" onclick= "this.src='captcha.php?act=captcha&'+Math.random()" style="cursor: pointer; vertical-align:middle" title="看不清?点击更换!" />

------解决方案--------------------
这个问题很诡异,最好的方法就是分开。
试试这个吧
checkcode.class.php

<?php
/**
 * 生成验证码
 * 类用法
 * $checkcode = new checkcode();
 * $checkcode->doimage();
 * //取得验证
 * $_SESSION['code']=$checkcode->get_code();
session_start();
include './checkcode.class.php';
$checkcode = new checkcode('C:\WINDOWS\Fonts\ARIAL.TTF');
$checkcode->doimage();
$_SESSION['code']=$checkcode->get_code();
 */
class checkcode {
//验证码的宽度
public $width=130;

//验证码的高
public $height=50;

//设置字体的地址
private $font;

//设置字体色
public $font_color;

//设置随机生成因子
public $charset = 'abcdefghkmnprstuvwyzABCDEFGHKLMNPRSTUVWYZ23456789';

//设置背景色
public $background = '#EDF7FF';

//生成验证码字符数
public $code_len = 4;

//字体大小
public $font_size = 20;

//验证码
private $code;

//图片内存
private $img;

//文字X轴开始的地方
private $x_start;

function __construct($fontpath) {
$this->font =$fontpath;
}
/**
 * 生成随机验证码。
 */
protected function creat_code() {
$code = '';
$charset_len = strlen($this->charset)-1;
for ($i=0; $i<$this->code_len; $i++) {
$code .= $this->charset[rand(1, $charset_len)];
}
$this->code = $code;
}

/**
 * 获取验证码
 */
public function get_code() {
return strtolower($this->code);
}

/**
 * 生成图片
 */
public function doimage() {
$code = $this->creat_code();
$this->img = imagecreatetruecolor($this->width,&nbs