2012-02-11 74 views
5

我有一個cronjob爲我的在線表單(註冊,聯繫人和通訊)生成驗證碼。imagemagick驗證碼

我每天生成超過5000張圖片,所以當我顯示錶格時,我隨機選擇一張圖片,然後只顯示圖片並設置會話。

我的表是非常簡單的:

驗證碼(ID MEDIUMINT(5)無符號PK,短語VARCHAR(10));

然後我運行生成圖像並插入數據庫的cronjob。這個過程需要一段時間來運行,我想知道是否有更好的方法來做到這一點,以最大限度地提高性能和代,因爲我有其他一整天運行的cronjob,並且我想確保我可以從cronjob所以我的cronjob工作可以呼吸一點。

+0

你爲什麼不使用gd? – 2012-02-11 02:15:55

+1

如果您總共有超過5000個聯繫人或通訊,那麼您很受歡迎:)這看起來效率相當低下,並且浪費資源。僅在需要時才生成圖像。 – Bakudan 2012-02-11 02:21:28

+0

以及我生成5000來確保當我隨機我不同一次兩次。 – Owan 2012-02-11 02:23:02

回答

8

創建一個文件調用Captcha.class.php,並把這個:

class Captcha { 
    private $font = '/path/to/font/yourfont.ttf'; // get any font you like and dont forget to update this. 

    private function generateCode($characters) { 
     $possible = '23456789bcdfghjkmnpqrstvwxyz'; // why not 1 and i, because they look similar and its hard to read sometimes 
     $code = ''; 
     $i = 0; 
     while ($i < $characters) { 
      $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1); 
      $i++; 
     } 
     return $code; 
    } 

    function getImage($width, $height, $characters) { 
     $code = $this->generateCode($characters); 
     $fontSize = $height * 0.75; 
     $image = imagecreate($width, $height); 
     if(!$image) { 
      return FALSE; 
     } 
     $background_color = imagecolorallocate($image, 255, 255, 255); 
     $text_color = imagecolorallocate($image, 66, 42, 32); 
     $noiseColor = imagecolorallocate($image, 150, 150, 150); 
     for($i=0; $i<($width*$height)/3; $i++) { 
      imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noiseColor); 
     } 
     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), $noiseColor); 
     } 
     $textbox = imagettfbbox($fontSize, 0, $this->font, $code); 
     if(!$textbox) { 
      return FALSE; 
     } 
     $x = ($width - $textbox[4])/2; 
     $y = ($height - $textbox[5])/2; 
     imagettftext($image, $fontSize, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function'); 
     header('Content-Type: image/jpeg'); 
     imagejpeg($image); 
     imagedestroy($image); 
     $_SESSION['captcha'] = $code; 
    } 
} 

然後在你的頁面,你可以這樣做:

<img src="/captcha.php" />

然後在/captcha.php你會把:

session_start(); 
require('Captcha.class.php'); 
$Captcha = new Captcha(); 
$Captcha->getImage(120,40,6); 

您可以隨時更改參數希望顯示不同的驗證碼。

這種方式,您將在飛行中生成。如果您願意,您也可以隨時將圖像保存在磁盤上。

+0

非常感謝你的伴侶 – Owan 2012-02-11 03:43:16

+0

不客氣 – 2012-02-11 03:43:55