php 给app写短信验证码 使用memcache缓存验证码

废话不多说  直接上代码 直接使用session 储存短信验证码,app  那边一直说获取不到 注册的时候一直提示空  后面想想还是用缓存吧 上代码:

//发送验证码方法   
public function sendSMSCodeOp(){

        require_once(BASE_ROOT_PATH.DS.'api/framework/function/sms.php');
        require_once(BASE_ROOT_PATH.DS.'api/framework/function/common.php');
        $sms = new sms();
        $_code = rand(100000, 999999);
        $_mobile = $_POST['mobile'];
        $_content = "【百城网】欢迎注册百城网,您的验证码为" . $_code;
        if(empty($_mobile)){
            $this->_message(CODE_ERROR,'手机号码不能空');
        }else{
            if(!isMobile($_mobile)){
                $this->_message(CODE_ERROR,'手机号码格式有误');
            }else{
                if($sms->sendSMS($_content, $_mobile)){
                   // $_SESSION['SMS_Code'] = $_code;
                    //$_SESSION['mobile'] = $_mobile;
                     //这一步写入缓存,由于服务器没有安装memcache,就用框架带的缓存机制来存储
                    $cache = Cache::getInstance(C('cache.type'));
                    $code_info = array();
                    $code_info['last_access'] = time();
                    $code_info['sms_mobile'] =  $_mobile;
                    $code_info['sms_mobile_code'] = $_code;
                    $cache->set($_mobile,$code_info);
                    $this->_printJson(CODE_SUCCESS,array("success"=>1),'短信验证码发送成功');
                }else{
                    $this->_message(CODE_ERROR,'验证码发送失败');
                }
            }

        }


    }




    /**
     * @param $mobile
     * @param $mobile_code
     * 验证验证码是否正确
     */
    private  function checkCode($mobile,$mobile_code){
    $obj_cache = Cache::getInstance(C('cache.type'));
    $obj = $obj_cache->get($mobile);

    if(empty($obj)){
        return array('error' => '您还未发送验证码');
    }else{
        if(!isset($obj['last_access'])||(time()-$obj['last_access'])>180*1000){
            return array('error' => '验证码已经失效');
        }else{
            if($mobile_code==$obj['sms_mobile_code'] && $mobile==$obj['sms_mobile'] ){

                return array("success"=>'验证通过');
            }else{
                return array('error' => '验证码错误');
            }
        }
    }
}



 

posted @ 2017-06-09 18:40  还好l  阅读(295)  评论(0编辑  收藏  举报