本帖最后由 Xdawei 于 2012-04-18 20:07:42 编辑
PHP 输出session 验证码与图片不同步,图片总是快一步,求解!
<br />
<?<br />
session_start();<br />
function random($len)<br />
{<br />
$srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";<br />
mt_srand();<br />
$strs="";<br />
for($i=0;$i<$len;$i++){<br />
$strs.=$srcstr[mt_rand(0,35)];<br />
}<br />
return strtoupper($strs);<br />
}<br />
$str=random(4); <br />
$width = 50; <br />
$height = 25; <br />
@header("Content-Type:image/png");<br />
$_SESSION["captcha"] = $str;<br />
//echo $str;<br />
$im=imagecreate($width,$height);<br />
$back=imagecolorallocate($im,0xFF,0xFF,0xFF);<br />
$pix=imagecolorallocate($im,187,230,247);<br />
$font=imagecolorallocate($im,41,163,238);<br />
mt_srand();<br />
for($i=0;$i<1000;$i++)<br />
{<br />
imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);<br />
}<br />
imagestring($im, 5, 7, 5,$str, $font);<br />
imagerectangle($im,0,0,$width-1,$height-1,$font);<br />
imagepng($im);<br />
imagedestroy($im);<br />
$_SESSION["captcha"] = $str;<br />
?><br />
<br />
<br />
<img src="captcha.php" style="max-width:90%" style="max-width:90%" border="1" onclick= "this.src='captcha.php?act=captcha&'+Math.random()" style="cursor: pointer; vertical-align:middle" title="看不清?点击更换!" / alt=" PHP 输出session 验证码与图片不同步,图片老是快一步,求解 " ><br />
------解决方案--------------------这个问题很诡异,最好的方法就是分开。
试试这个吧
checkcode.class.php
<br>
<?php <br />
/**<br>
* 生成验证码<br>
* 类用法<br>
* $checkcode = new checkcode();<br>
* $checkcode->doimage();<br>
* //取得验证<br>
* $_SESSION['code']=$checkcode->get_code();<br>
session_start();<br>
include './checkcode.class.php';<br>
$checkcode = new checkcode('C:\WINDOWS\Fonts\ARIAL.TTF');<br>
$checkcode->doimage();<br>
$_SESSION['code']=$checkcode->get_code();<br>
*/<br>
class checkcode {<br>
//验证码的宽度<br>
public $width=130;<br>
<br>
//验证码的高<br>
public $height=50;<br>
<br>
//设置字体的地址<br>
private $font;<br>
<br>
//设置字体色<br>
public $font_color;<br>
<br>
//设置随机生成因子<br>
public $charset = 'abcdefghkmnprstuvwyzABCDEFGHKLMNPRSTUVWYZ23456789';<br>
<br>
//设置背景色<br>
public $background = '#EDF7FF';<br>
<br>
//生成验证码字符数<br>
public $code_len = 4;<br>
<br>
//字体大小<br>
public $font_size = 20;<br>
<br>
//验证码<br>
private $code;<br>
<br>
//图片内存<br>
private $img;<br>
<br>
//文字X轴开始的地方<br>
private $x_start;<br>
<br>
function __construct($fontpath) {<br>
$this->font =$fontpath;<br>
}<br>
/**<br>
* 生成随机验证码。<br>
*/<br>
protected function creat_code() {<br>
$code = '';<br>
$charset_len = strlen($this->charset)-1;<br>
for ($i=0; $icode_len; $i++) {<br>
$code .= $this->charset[rand(1, $charset_len)];<br>
}<br>
$this->code = $code;<br>
}<br>
<br>
/**<br>
* 获取验证码<br>
*/<br>
public function get_code() {<br>
return strtolower($this->code);<br>
}<br>
<br>
/**<br>
* 生成图片<br>
*/<br>
public function doimage() {<br>
$code = $this->creat_code();<br>
$this->img = imagecreatetruecolor($this->width, $this->height);<br>
if (!$this->font_color) { <div class="clear">
</div>