2012-12-05 43 views
0

我使用驗證碼的組成部分。CakePHP的captca驗證

<?php 

function create($width='120',$height='40',$characters='6') { 

    $code = $this->generateCode($characters); 

    /* font size will be 75% of the image height */ 
    $font_size = $height * 0.70; 

    $image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream'); 

    /* set the colours */ 
    $background_color = imagecolorallocate($image, 220, 220, 220);    
    $text_color  = imagecolorallocate($image, 10, 30, 80); 
    $noise_color  = imagecolorallocate($image, 150, 180, 220); 

    /* generate random dots in background */ 
    for($i=0; $i<($width*$height)/3; $i++) { 
     imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color); 
    } 

    /* generate random lines in background */ 
    for($i=0; $i<($width*$height)/150; $i++) { 
     imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color); 
    } 

    /* create textbox and add text */ 
    $textbox = imagettfbbox($font_size, 0, dirname(__FILE__).'/'.$this->font, $code) or die('Error in imagettfbbox function'); 
    $x  = ($width - $textbox[4])/2; 
    $y  = ($height - $textbox[5])/2; 
    $y  -= 5; 
    imagettftext($image, $font_size, 0, $x, $y, $text_color, dirname(__FILE__).'/'.$this->font , $code) or die('Error in imagettftext function'); 

    /* output captcha image to browser */ 
    header('Content-Type: image/jpeg'); 
    imagejpeg($image); 
    imagedestroy($image); 

    $this->Controller->Session->write('security_code',$code); 
} 

的captca創建成功,但是當我嘗試驗證它,我得到了一個錯誤,因爲$code沒有存儲在會話。我不明白爲什麼會發生這種情況。

+0

那不是真正的好代碼擺脫這一點。腳本仍在工作時,您不應發送標題等。這就是爲什麼你不在2.x中手動發送任何頭文件並讓響應類去做的原因。 – mark

回答

0

變化:

$this->Controller->Session->write('security_code', $code); 

這樣:

$this->Session->write('security_code', $code); 

同時,還要確保你已經添加了SessionHelper到$助手陣列。

0

如果您正在使用CakePHP 1.x中,似乎您的應用程序將輸出發送到瀏覽器中的header()函數之前被調用來生成圖像。在這種情況下,您需要將會話創建線移動到標題('Content-Type:image/jpeg');看起來像下面這樣:

imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function'); 
/* output captcha image to browser */ 
$this->Controller->Session->write('security_code',$code); 
@ob_end_clean(); //clean buffers, as a fix for 'headers already sent errors..' 
header('Content-Type: image/jpeg'); 
imagejpeg($image); 
imagedestroy($image); 

如果您正在使用驗證碼組件CakePHP的2.x的下載更新版本從作者的網站www.devarticles.in/cakephp/simple-captcha-component-for-cakephp/

0

我也遇到了一些問題,並得到由這裏改變會話存儲行的位置

function create($width='120',$height='40',$characters='6') { 

    $code = $this->generateCode($characters); 
    $this->Controller->Session->write('security_code',$code); 

    //.....rest of code will remain same 
}