RESTful API格式 圖片驗證碼介面

來源:互聯網
上載者:User

標籤:session   迴圈   default   pwd   畫像   rom   距離   顏色   成功   

 

之前公司寫圖片驗證碼時用的是session

後來寫介面時也想用session存驗證碼  不過領導說RESTful API 寫介面 沒有session這一說 於是就用了redis 存驗證碼

還有就是介面需要傳回值

不能直接把圖片顯示出來 這時需要對圖片驗證碼進行base64轉碼處理 返回base64的值 然後他們前端再調用 

===================================================================================================================

在Thinkphp架構裡找了個驗證碼類 修改了一下 

產生驗證碼(字型檔可以去thinkphp架構裡提取):

<?php/** *@descrption : 驗證碼產生類 *@author     : Mark.liu */date_default_timezone_set(‘PRC‘);require_once(‘/data/redis/RedisConfig.php‘);class Verify {    protected $config = array(        ‘seKey‘     =>  ‘888888‘,   // 驗證碼加密金鑰        ‘codeSet‘   =>  ‘2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY‘,             // 驗證碼字元集合        ‘expire‘    =>  1800,            // 驗證碼到期時間(s)        ‘useZh‘     =>  false,           // 使用中文驗證碼        ‘zhSet‘     =>  ‘‘,              // 中文驗證碼字串        ‘useImgBg‘  =>  false,           // 使用背景圖片        ‘fontSize‘  =>  25,              // 驗證碼字型大小(px)        ‘useCurve‘  =>  true,            // 是否畫混淆曲線        ‘useNoise‘  =>  true,            // 是否添加雜點        ‘imageH‘    =>  0,               // 驗證碼圖片高度        ‘imageW‘    =>  0,               // 驗證碼圖片寬度        ‘length‘    =>  5,               // 驗證碼位元        ‘fontttf‘   =>  ‘‘,              // 驗證碼字型,不設定隨機擷取        ‘bg‘        =>  array(243, 251, 254),  // 背景顏色        ‘reset‘     =>  true,           // 驗證成功後是否重設    );    private $_image   = NULL;     // 驗證碼圖片執行個體    private $_color   = NULL;     // 驗證碼字型顏色    /**     * 架構方法 設定參數     * @access public     * @param  array $config 配置參數     */    public function __construct($config=array()){        $this->config   =   array_merge($this->config, $config);    }    /**     * 使用 $this->name 擷取配置     * @access public     * @param  string $name 配置名稱     * @return multitype    配置值     */    public function __get($name) {        return $this->config[$name];    }    /**     * 設定驗證碼配置     * @access public     * @param  string $name 配置名稱     * @param  string $value 配置值     * @return void     */    public function __set($name,$value){        if(isset($this->config[$name])) {            $this->config[$name]    =   $value;        }    }    /**     * 檢查配置     * @access public     * @param  string $name 配置名稱     * @return bool     */    public function __isset($name){        return isset($this->config[$name]);    }    /**     * redis串連     * @return     */    public function  _redis()    {        $redis = new Redis;        $hosts = RedisServerConfig::SERVER_HOST;        $port = RedisServerConfig::SERVER_PORT;        $pwd = RedisServerConfig::SERVER_PASS;        $redis->connect($hosts,$port);        $redis->auth($pwd);        return $redis;    }    /**     * 驗證驗證碼是否正確     * @access public     * @param string $code 使用者驗證碼     * @param string $id 驗證碼標識     * @return bool 使用者驗證碼是否正確     */    public function check($code, $id = ‘‘) {        $key = $this->authcode($this->seKey).$id;        $redis = $this->_redis();        $_val = $redis->get($key);        if(empty($_val))        {            return false;        }        $secode = json_decode($_val,true);        if(empty($code) || empty($secode)) {            return false;        }        // session 到期        $NOW_TIME = time();        if($NOW_TIME - $secode[‘verify_time‘] > $this->expire) {            // unset($_SESSION[$key]);            $redis->expire($key,0);            // session($key, null);            return false;        }        if($this->authcode(strtoupper($code)) == $secode[‘verify_code‘]) {            // $this->reset && session($key, null);            // unset($_SESSION[$key]);            $redis->expire($key,0);            return true;        }        return false;    }    /**     * 輸出驗證碼並把驗證碼的值儲存的session中     * 驗證碼儲存到session的格式為: array(‘verify_code‘ => ‘驗證碼值‘, ‘verify_time‘ => ‘驗證碼建立時間‘);     * @access public     * @param string $id 要產生驗證碼的標識     * @return void     */    public function entry($id = ‘‘) {        // 圖片寬(px)        $this->imageW || $this->imageW = $this->length*$this->fontSize*1.5 + $this->length*$this->fontSize/2;        // 圖片高(px)        $this->imageH || $this->imageH = $this->fontSize * 2.5;        // 建立一幅 $this->imageW x $this->imageH 的映像        $this->_image = imagecreate($this->imageW, $this->imageH);        // 設定背景        imagecolorallocate($this->_image, $this->bg[0], $this->bg[1], $this->bg[2]);        // 驗證碼字型隨機顏色        $this->_color = imagecolorallocate($this->_image, mt_rand(1,150), mt_rand(1,150), mt_rand(1,150));        // 驗證碼使用隨機字型        $ttfPath = dirname(__FILE__) . ‘/Verify/‘ . ($this->useZh ? ‘zhttfs‘ : ‘ttfs‘) . ‘/‘;        if(empty($this->fontttf)){            $dir = dir($ttfPath);            $ttfs = array();            while (false !== ($file = $dir->read())) {                if($file[0] != ‘.‘ && substr($file, -4) == ‘.ttf‘) {                    $ttfs[] = $file;                }            }            $dir->close();            $this->fontttf = $ttfs[array_rand($ttfs)];        }        $this->fontttf = $ttfPath . $this->fontttf;        if($this->useImgBg) {            $this->_background();        }        if ($this->useNoise) {            // 繪雜點            $this->_writeNoise();        }        if ($this->useCurve) {            // 繪幹擾線            $this->_writeCurve();        }        // 繪驗證碼        $code = array(); // 驗證碼        $codeNX = 0; // 驗證碼第N個字元的左邊距        if($this->useZh){ // 中文驗證碼            for ($i = 0; $i<$this->length; $i++) {                $code[$i] = iconv_substr($this->zhSet,floor(mt_rand(0,mb_strlen($this->zhSet,‘utf-8‘)-1)),1,‘utf-8‘);                imagettftext($this->_image, $this->fontSize, mt_rand(-40, 40), $this->fontSize*($i+1)*1.5, $this->fontSize + mt_rand(10, 20), $this->_color, $this->fontttf, $code[$i]);            }        }else{            for ($i = 0; $i<$this->length; $i++) {                $code[$i] = $this->codeSet[mt_rand(0, strlen($this->codeSet)-1)];                $codeNX  += mt_rand($this->fontSize*1.2, $this->fontSize*1.6);                imagettftext($this->_image, $this->fontSize, mt_rand(-40, 40), $codeNX, $this->fontSize*1.6, $this->_color, $this->fontttf, $code[$i]);            }        }        // 儲存驗證碼        $key        =   $this->authcode($this->seKey);        $code       =   $this->authcode(strtoupper(implode(‘‘, $code)));        $secode     =   array();        $secode[‘verify_code‘] = $code; // 把校正碼儲存到session        $secode[‘verify_time‘] = time();  // 驗證碼建立時間        $redis = $this->_redis();        $redis->set($key.$id,json_encode($secode));        header(‘Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate‘);        header(‘Cache-Control: post-check=0, pre-check=0‘, false);        header(‘Pragma: no-cache‘);        ob_start();        imagepng($this->_image);        $image_data = ob_get_contents();        ob_end_clean();        //$base64 = base64_encode($imagedata);        $image_data_base64 = ‘data:image/png;base64,‘.base64_encode ($image_data);        return $image_data_base64;    }    /**     * 畫一條由兩條連在一起構成的隨機正弦函數曲線作幹擾線(你可以改成更帥的曲線函數)     *     *      高中的數學公式咋都忘了涅,寫出來     *      正弦型函數解析式:y=Asin(ωx+φ)+b     *      各常數值對函數映像的影響:     *        A:決定峰值(即縱向展開壓縮的倍數)     *        b:表示波形在Y軸的位置關係或縱向移動距離(上加下減)     *        φ:決定波形與X軸位置關係或橫向移動距離(左加右減)     *        ω:決定周期(最小正周期T=2π/∣ω∣)     *     */    private function _writeCurve() {        $px = $py = 0;        // 曲線前部分        $A = mt_rand(1, $this->imageH/2);                  // 振幅        $b = mt_rand(-$this->imageH/4, $this->imageH/4);   // Y軸方向位移量        $f = mt_rand(-$this->imageH/4, $this->imageH/4);   // X軸方向位移量        $T = mt_rand($this->imageH, $this->imageW*2);  // 周期        $w = (2* M_PI)/$T;        $px1 = 0;  // 曲線橫座標起始位置        $px2 = mt_rand($this->imageW/2, $this->imageW * 0.8);  // 曲線橫座標結束位置        for ($px=$px1; $px<=$px2; $px = $px + 1) {            if ($w!=0) {                $py = $A * sin($w*$px + $f)+ $b + $this->imageH/2;  // y = Asin(ωx+φ) + b                $i = (int) ($this->fontSize/5);                while ($i > 0) {                    imagesetpixel($this->_image, $px + $i , $py + $i, $this->_color);  // 這裡(while)迴圈畫像素點比imagettftext和imagestring用字型大小一次畫出(不用這while迴圈)效能要好很多                    $i--;                }            }        }        // 曲線後部分        $A = mt_rand(1, $this->imageH/2);                  // 振幅        $f = mt_rand(-$this->imageH/4, $this->imageH/4);   // X軸方向位移量        $T = mt_rand($this->imageH, $this->imageW*2);  // 周期        $w = (2* M_PI)/$T;        $b = $py - $A * sin($w*$px + $f) - $this->imageH/2;        $px1 = $px2;        $px2 = $this->imageW;        for ($px=$px1; $px<=$px2; $px=$px+ 1) {            if ($w!=0) {                $py = $A * sin($w*$px + $f)+ $b + $this->imageH/2;  // y = Asin(ωx+φ) + b                $i = (int) ($this->fontSize/5);                while ($i > 0) {                    imagesetpixel($this->_image, $px + $i, $py + $i, $this->_color);                    $i--;                }            }        }    }    /**     * 畫雜點     * 往圖片上寫不同顏色的字母或數字     */    private function _writeNoise() {        $codeSet = ‘2345678abcdefhijkmnpqrstuvwxyz‘;        for($i = 0; $i < 10; $i++){            //雜點顏色            $noiseColor = imagecolorallocate($this->_image, mt_rand(150,225), mt_rand(150,225), mt_rand(150,225));            for($j = 0; $j < 5; $j++) {                // 繪雜點                imagestring($this->_image, 5, mt_rand(-10, $this->imageW),  mt_rand(-10, $this->imageH), $codeSet[mt_rand(0, 29)], $noiseColor);            }        }    }    /**     * 繪製背景圖片     * 註:如果驗證碼輸出圖片比較大,將佔用比較多的系統資源     */    private function _background() {        $path = dirname(__FILE__).‘/Verify/bgs/‘;        $dir = dir($path);        $bgs = array();        while (false !== ($file = $dir->read())) {            if($file[0] != ‘.‘ && substr($file, -4) == ‘.jpg‘) {                $bgs[] = $path . $file;            }        }        $dir->close();        $gb = $bgs[array_rand($bgs)];        list($width, $height) = @getimagesize($gb);        // Resample        $bgImage = @imagecreatefromjpeg($gb);        @imagecopyresampled($this->_image, $bgImage, 0, 0, 0, 0, $this->imageW, $this->imageH, $width, $height);        @imagedestroy($bgImage);    }    /* 加密驗證碼 */    private function authcode($str){        $key = substr(md5($this->seKey), 5, 8);        $str = substr(md5($str), 8, 10);        return md5($key . $str);    }}

調用產生圖片驗證碼:

 

<?php$codeId = 1; //可以根據不同使用情境傳不同的ID$infos = new Verify;$base64Data = $infos->entry($codeId);$returnData = [ ‘imgSrc‘=>$base64Data ];

 

 

校正驗證碼:

 

<?php$verifyCode = new Verify;if(!$verifyCode->check($confirmCode,$confirmCodeId)){   echo ‘驗證碼錯誤‘;}

 

  

 

RESTful API格式 圖片驗證碼介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.