RESTful API Format Picture Verification Code interface

Source: Internet
Author: User
Tags asin set background

Before the company wrote a picture verification code with the session

Later write the interface also want to use the session to save the verification code but the leader said that the restful API write interface does not have a session this said to use the Redis Memory verification code

And the interface needs a return value.

You can't just show the picture. The Base64 transcoding of the image verification code is required to return the value of Base64 and then they call the front end.

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

In the thinkphp framework, we've got a verification code class modified.

Generate Verification code (font files can be extracted in the thinkphp framework):

<?php/** * @descrption: Verification code Generation class * @author: Mark.liu */date_default_timezone_set (' PRC '); require_once ('/data/redis/re Disconfig.php '), class Verify {protected $config = Array (' sekey ' = ' 888888 ',//CAPTCHA encryption key ' code Set ' = ' 2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY ',//captcha Character set ' expire ' = 180              0,//Verification code expiry time (s) ' Usezh ' + false,//use Chinese captcha ' zhset ' = ', Chinese captcha string ' useimgbg ' = false,//Use background image ' FontSize ' + 25,//Captcha font size ( px) ' usecurve ' = true,//whether to draw the confusion curve ' usenoise ' = = true,//whether to add the miscellaneous dot ' ima  Geh ' + 0,//captcha image height ' Imagew ' + 0,//captcha image width ' length ' = 5,//Verify code bits ' Fontttf ' + ',//Captcha font, do not set random get ' bg ' = = Array (243    , 251, 254),//Background color    ' Reset ' = true,//verify if the reset is successful;     Private $_image = NULL;     Verification code Picture Instance Private $_color = NULL; CAPTCHA Font Color/** * Schema method setting parameters * @access public * @param array $config configuration parameters */Public Function __constr    UCT ($config =array ()) {$this->config = Array_merge ($this->config, $config);     /** * Use $this->name to get configuration * @access public * @param string $name configuration name * @return Multitype configuration value    */Public Function __get ($name) {return $this->config[$name]; /** * Set CAPTCHA configuration * @access public * @param string $name configuration name * @param string $value configuration value * @return void */Public Function __set ($name, $value) {if (Isset ($this->config[$name])) {$this->confi        g[$name] = $value;  }}/** * Check configuration * @access public * @param string $name configuration name * @return BOOL */Public function __isset ($name) {return isset ($this-> config[$name]);        /** * Redis Connection * @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; }/** * Verify that the verification code is correct * @access public * @param string $code User Verification code * @param string $id authenticode identification * @return        BOOL User Verification Code is correct */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 expires $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 ($code) = = = $secode [' Verify_code ']) {//$this->reset && SE            Ssion ($key, NULL);            Unset ($_session[$key]);            $redis->expire ($key, 0);        return true;    } return false; }/** * Output the verification code and save the value of the verification code in the session * verification code saved to session format: Array (' verify_code ' = ' Verification Code value ', ' verify_time ' = ' + ' verification code)     Creation time '); * @access public * @param string $id the identification to generate the verification code * @return void */Public Function entry ($id = ') {/ /Picture width (px) $this->imagew | |        $this->imagew = $this->length* $this->fontsize*1.5 + $this->length* $this->fontsize/2; Picture height (px) $this->imageh | |        $this->imageh = $this->fontsize * 2.5; Create an image $this->imagew x $this->imageh $this->_image = imagecreate ($this->imagew, $this->imageh);        Set Background imagecolorallocate ($this->_image, $this->bg[0], $this->bg[1], $this->bg[2]); CAPTCHA font random color $this->_color = imagecolorallocate ($this->_image, Mt_rand (1,150), Mt_rand (1,150), Mt_rand (1,150)        ); The captcha uses a random font $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) {//Plot dot $this->_writenoise ();       } if ($this->usecurve) {//Draw interference line $this->_writecurve (); }//Draw verification Code $code = Array (); Verification code $codeNX = 0;                Verification code The nth character of the left margin if ($this->usezh) {//Chinese code 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, +), $this->fontsize* ($i + 1) *1.5, $this-            FontSize + Mt_rand (Ten), $this->_color, $this->fontttf, $code [$i]); }}else{for ($i = 0; $i < $this->length; $i + +) {$code [$i] = $this->codeset[mt_ra                nd (0, strlen ($this->codeset)-1)];                $codeNX + = Mt_rand ($this->fontsize*1.2, $this->fontsize*1.6); Imagettftext ($this->_image, $this->fontsize, Mt_rand ( -40, +), $codeNX, $this->fontsize*1.6, $this->_ Color, $this->fontttf, $code[$i]);        }}//Save verification Code $key = $this->authcode ($this->sekey);        $code = $this->authcode (strtoupper (Implode (", $code)));        $secode = Array (); $secode [' verify_code '] = $code;  Save the check code to session $secode [' verify_time '] = time ();        Verification code creation 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 ();        $base = Base64_encode ($imagedata);        $image _data_base64 = ' data:image/png;base64, '. Base64_encode ($image _data);    return $image _data_base64; }/** * Draw a random sine function curve consisting of two lines as the interfering line (you can change to a more handsome curve function) * * High school math formula I forgot Nirvana, write it out * sine type function analytic: y=asIn (ωx+φ) +b * The effect of each constant value on the function image: * A: Determines the peak (that is, the multiple of the longitudinal stretch compression) * B: Indicates the position of the waveform on the Y axis or the longitudinal movement distance (upper plus minus) * Φ: Determines the position of the waveform with the x-axis or transverse moving distance (left plus right minus) *ω: Decision period (minimum positive period t=2π/∣ω∣) * */Private Function _writecurve () {$px        = $py = 0;                  The front part of the curve $A = Mt_rand (1, $this-&GT;IMAGEH/2);   Amplitude $b = Mt_rand (-$this-&GT;IMAGEH/4, $this-&GT;IMAGEH/4);   Y-axis direction offset $f = Mt_rand (-$this-&GT;IMAGEH/4, $this-&GT;IMAGEH/4);  X-axis direction Offset $T = Mt_rand ($this->imageh, $this->imagew*2);        Cycle $w = (M_PI)/$T;  $px 1 = 0;  Curve horizontal start position $px 2 = Mt_rand ($this->imagew/2, $this->imagew * 0.8); Curve horizontal end position for ($px = $px 1; $px <= $px 2; $px = $px + 1) {if ($w!=0) {$py = $A * Sin ($w  * $px + $f) + $b + $this->imageh/2;                y = Asin (ωx+φ) + b $i = (int) ($this-&GT;FONTSIZE/5); while ($i > 0) {imagesetpixel ($this->_image, $px + $i, $py + $i, $this->_color);                This (while) loop is much better than Imagettftext and imagestring to draw (without this while loop) at one time with the font size $i-;                  }}}//curve after section $A = Mt_rand (1, $this-&GT;IMAGEH/2);   Amplitude $f = Mt_rand (-$this-&GT;IMAGEH/4, $this-&GT;IMAGEH/4);  X-axis direction Offset $T = Mt_rand ($this->imageh, $this->imagew*2);        Cycle $w = (M_PI)/$T;        $b = $py-$A * sin ($w * $px + $f)-$this->imageh/2;        $PX 1 = $px 2;        $px 2 = $this->imagew; for ($px = $px 1; $px <= $px 2; $px = $px + 1) {if ($w!=0) {$py = $A * Sin ($w * $px + $f) + $b + $this-  >imageH/2;                y = Asin (ωx+φ) + b $i = (int) ($this-&GT;FONTSIZE/5);                    while ($i > 0) {imagesetpixel ($this->_image, $px + $i, $py + $i, $this->_color);                $i--; }}}}/** * Draw the dots * to write letters or numbers of different colors on the picture */privAte function _writenoise () {$codeSet = ' 2345678abcdefhijkmnpqrstuvwxyz '; for ($i = 0; $i < $i + +) {//DOT color $noiseColor = imagecolorallocate ($this->_image, Mt_rand (150            , 225), Mt_rand (150,225), Mt_rand (150,225)); for ($j = 0; $j < 5; $j + +) {//Plot point imagestring ($this->_image, 5, Mt_rand ( -10, $this-&G            T;imagew), Mt_rand ( -10, $this->imageh), $codeSet [Mt_rand (0)], $noiseColor); }}}/** * Draw background image * Note: If the verification code output picture is larger, will occupy more system resources */Private Function _background () {$PA th = 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);        }/* Cryptographic Verification Code */Private Function Authcode ($str) {$key = substr (MD5 ($this->sekey), 5, 8);        $STR = substr (MD5 ($STR), 8, 10);    return MD5 ($key. $str); }}

Call to generate a picture verification code:

<?php$codeid = 1; Can be used according to different use of different Id$infos = new Verify; $base 64Data = $infos->entry ($codeId); $returnData = [' imgsrc ' = + $base 64Data ];

 

Verification Code:

<?php$verifycode = new Verify;if (! $verifyCode->check ($confirmCode, $confirmCodeId)) {   echo ' Verification code error ';}

  

RESTful API Format Picture Verification Code interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.