1. 程式人生 > >PHP生成圖片驗證碼

PHP生成圖片驗證碼

PHP生成圖片驗證碼

分為兩個方法函式

<?php
/**
 * PHP生成圖片驗證碼
 * Class VerifyImage
 */
class VerifyImage
{
    // 生成隨機字串
    private $verifyCode;
    // 圖片物件
    private $image;

    /**
     * todo:生成隨機驗證碼
     * @param int $type 型別 【1】純數字,【2】純字母,【3】數字加字母
     * @param int $length
     * @return bool|string
     */
    public function createCode($type = 3, $length = 5)
    {
        if ($type == 1) {
            $verifyCode = implode('', range(0, 9));
        } elseif ($type == 2) {
            $verifyCode = implode('', array_merge(range('a', 'z'), range('A', 'Z')));
        } else {
            $verifyCode = implode('', array_merge(range('a', 'z'), range(0, 9), range('A', 'Z')));
        }

        //判斷生成字元是否符合要求
        if (strlen($verifyCode) < $length) {
            return false;
        }
        //打亂字串
        $verifyCode = str_shuffle($verifyCode);
        $this->verifyCode = substr($verifyCode, 0, $length);
        return $this->verifyCode;
    }

    /**
     * todo:加入字元,生成圖片,並加入干擾線,干擾素
     * @param int $width 圖片寬度
     * @param int $height 圖片高度
     */
    public function createImage($width = 80, $height = 30)
    {
        $verifyCode = $this->verifyCode;
        $image      = imagecreatetruecolor($width, $height);

        //白色背景
        $white = imagecolorallocate($image, 255, 255, 255);
        //字型顏色
        $fontStyle = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));;
        imagefill($image, 0, 0, $white);
        // 使用預設字型,無法修改文字大小
        // imagestring($image, 5, 10, 10, $verifyCode, $fontStyle);
        // 匯入自定義字型,修改文字大小
        imagettftext($image, 24, 0, 5, 20, $fontStyle, '../microsofthimalaya.ttf', $verifyCode);
        //加入干擾點
        for ($i = 0; $i < 80; $i++) {
            $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($image, rand(0, $width), rand(0, $height), $color);
        }
        //干擾線
        for ($i = 0; $i < 5; $i++) {
            $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $color);
        }
        //輸出圖片
        header("Content-type: image/png");
        imagepng($image);
        //釋放資源
        imagedestroy($image);
    }
}

?>

例項

$VerifyImage = new VerifyImage();
$code = $VerifyImage->createCode();
$_SESSION['$VerifyCode'] = $code;
$VerifyImage->createImage();