PHP 如何實現圖形驗證碼


封裝驗證碼函數

<?php
/*
    驗證碼
    寬 高 字母 數字 字母數字混合 干擾線 干擾點 背景色(要比字體顏色淺) 字體的顏色
*/
/**
  * @param $width:寬
  * @param $height:高
  * @param $num:顯示多少位
  * @param $type:類型 1數字,2字母,3數字大小寫字母
*/
verify();
function verify($width = 100,$height = 40,$num = 5,$type = 3){
    // 1. 准備畫布
    $image = imagecreatetruecolor($width, $height); // 設置驗證碼圖片大小的函數
    // 2. 生成顏色(背景填充顏色,字體顏色)
    imagefilledrectangle($image, 0, 0, $width, $height, lightColor($image));// 畫一矩形並填充
    // 3. 你需要什么樣的字符
    $string = '';
    switch($type){
        case 1:
            $str = '0123456789';
            $string = substr(str_shuffle($str), 0 ,$num);
            break;
        case 2:
            $arr = range('a','z');
            shuffle($arr);
            $tmp = array_slice($arr,0,5);
            $string = join('', $tmp);
            break;
        case 3:
            // 0-9 a-z A-Z 
            $str = '0123456789abcdefghizklmnopqrstuvwxyzABCDEFGHIZKLMNOPQRSTUVWXYZ'; // 也可取出類似的0il
            $string = substr(str_shuffle($str),0,$num);
            break;
    }
    // 4. 開始寫字
    $fontsize = 16; // 字大小
    for($i = 0;$i < $num;$i++){
        $x = floor($width / $num) * $i + 4;
        $y = mt_rand(10, $height - 20);
        imagechar($image, $fontsize, $x, $y, $string[$i], deepColor($image));// 水平低畫一個字符
    }
    // 5. 干擾線(點)
    for($i = 0;$i < $num;$i++){
        imagearc($image, mt_rand(10, $width), mt_rand(10, $height), mt_rand(10, $width), mt_rand(10, $height), mt_rand(0, 10), mt_rand(0, 270), deepColor($image));// 畫橢圓弧
    }
    for($i = 0;$i < 50;$i++){
        imagesetpixel($image, mt_rand(10, $width), mt_rand(10, $height), deepColor($image));// 畫一個單一像素
    }
    // 6. 指定輸出的類型
    header('Content-type:image/png');
    // 7. 准備輸出圖片
    imagepng($image);
    // 8. 銷毀
    imagedestroy($image); // 結束圖形函數 銷毀$image

    return $string;
}
// 淺色
function lightColor($image){
    return imagecolorallocate($image, mt_rand(130, 255),mt_rand(130, 255), mt_rand(130, 255)); // 為一幅圖像分配顏色
}
// 深色
function deepColor($image){
    return imagecolorallocate($image, mt_rand(0, 120),mt_rand(0, 120), mt_rand(0, 120));
}
// 如果報錯Call to undefined function imagecreatetruecolor(),請開啟php.int extension=gd2


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM