PHP 輸出session 驗證碼與圖片不同步,圖片老是快一步,求解

來源:互聯網
上載者:User
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;
?>






------解決方案--------------------
這個問題很詭異,最好的方法就是分開。
試試這個吧
checkcode.class.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, $this->height);
if (!$this->font_color) {
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.