用於防止網站自動註冊的驗證碼產生。
函式參數如下:
$code - 您要隨機產生的驗證碼
$location - 要產生的圖片的相對位置
$fonts_dir - GDF 字型目錄的相對位置
此函式將建立一個包含您提供的驗證碼的圖片,並將其儲存在指定的目錄中,檔案名稱由驗證碼的 MD5 雜湊值組成。
您可以在字型目錄中插入任意數量的字型類型,並使用隨機名稱。
<?php
function generate_image($code, $location, $fonts_dir)
{
$image = imagecreate(150, 60);
imagecolorallocate($image, rand(0, 100), rand(100, 150), rand(150, 250));
$fonts = scandir($fonts_dir);
$max = count($fonts) - 2;
$width = 10;
for ($i = 0; $i <= strlen($code); $i++)
{
$textcolor = imagecolorallocate($image, 255, 255, 255);
$rand = rand(2, $max);
$font = imageloadfont($fonts_dir."/".$fonts[$rand]);
$fh = imagefontheight($font);
$fw = imagefontwidth($font);
imagechar($image, $font, $width, rand(10, 50 - $fh), $code[$i], $textcolor);
$width = $width + $fw;
}
imagejpeg($image, $location."/".md5($code).".jpg", 100);
imagedestroy($image);
return $code;
}
?>