手机短信接收验证码的实现原理:

时间:2024-02-16 08:10:17

关于手机短信接收验证码的实现原理:
思路:
A:获得验证码:
1.找到相关的表。
2.用什么发送,post,get ,ajax,当然ajax首选
3.post之前要js先判断是手机号码11位,并且全部都是数字,或者用正则也行。
4.用ajax发送数据data,要对数据进行检验,过滤有效数据valid
5.insert前要先判断这手机是否验证过了,已经验证过就return false;没验证过则把随机生成的6位验证码insert 数据库表中。
6.通过提供给你api写好调用,把验证码跟msg通过ajax返回值发送给向客户,并用js做一个倒计时计数器.

B:接收验证码,提交表单:
1.接收post过来数据,把验证码跟跟刚才插入数据库中的6位key进行比较。如果相等,则说明是最后一次发送的验证码才有效。
2.对数据库insert 操作.最少要做个认证tag标志.

 

先贴出html部分:

 <!--手机认证 Begin-->
      <div style="display: block;" class="auth_ck_detail" id="auth_ck_phone">
        <div class="item_title item_margin"><p>手机认证</p><span class="shadow"></span></div>
        <form name="myform" id="myform" action="http://www.hnb.cc/jiaoyou/usercp.php?c=certify&amp;a=rzmobile" method="post">
            <table class="user-table table-margin lh35" border="0" cellpadding="0" cellspacing="0" width="98%">
                <tbody>
                    <tr>
                        <td class="lblock" width="15%">您的手机号码:</td>
                        <td class="rblock" width="85%">

                            <input name="mobile" id="mobile" value="" class="input-150" type="text" style="width:130px;"> &nbsp;&nbsp;

                            <input name="btn_downtime" id="btn_downtime" value="免费获取验证码" style="height: 25px; background:#F5487A; color:#fff; padding-left: 2px; padding-right: 5px; width:175px;" class="button-green-b" type="button"> <span id="tips_mobile"></span>

                            <br>
                            <div class="mb-verifycode" style=" width:320px; background:#FFDD55;margin-top:10px; color:#666666; padding-left:10px; padding-bottom:5px;" >
                                <p style="font-size:13px;">输入以下图片校验码才可以获取手机验证码</p>
                                <dl style=" float:left;">
                                    <dt style=" float:left;">校验码:</dt>
                                    <dd style=" float:left;   "><input  style="width:100px; " value="" name="mbverifycode" id="mbverifycode" maxlength="6" type="text"> <img id="verifycode-img" src="#" style="vertical-align: middle;"> <span id="btn_mbverifycode" >换一个</span></dd>
                                    <div style="clear: both;"></div>
                                </dl>
                                <div style="clear: both;"></div>
                            </div>

                        </td>
                    </tr>
                    <tr>

                        <td class="lblock">收到的验证码:</td>
                        <td class="rblock"><input value="" name="checkcode" id="checkcode" class="input-s" type="text"> <font color="#df4070">(输入您手机收到的验证码)</font></td>
                    </tr>
                    <tr>
                        <td class="lblock" height="40"></td>
                        <td class="rblock"><input value="提交验证" onclick="return checkrzmobile();" class="button-gray" type="button"></td>
                    </tr>
                </tbody>
            </table>
        </form>

        <table class="user-table table-margin lh25" border="0" cellpadding="0" cellspacing="0" width="98%">
          <tbody><tr>
            <td>
                为什么要进行手机认证?<br>
                1、认证通过后可在您的资料页点亮手机认证图标,提高你的诚信等级;<br>
                2、接收来自网站和会员发送的手机短信。<br>
            </td>
          </tr>
        </tbody></table>

        <script type="text/javascript">
        //处理手机验证码
        $("#verifycode-img").attr("src", "/jiaoyou/source/include/imagecode.php?act=verifycode&t_code="+(new Date()).getTime());
        $(function()
        {
            $("#btn_mbverifycode").click(function()
            {
                
                $("#verifycode-img").attr("src", "/jiaoyou/source/include/imagecode.php?act=verifycode&t_code="+(new Date()).getTime());
                    return false;

            });
            
                

            $("#btn_downtime").click(function()
            { //获取手机验证码
                var tips = $("#tips_mobile");
                var args_mobile = $("#mobile").val();
                var args_mbverifycode = $("#mbverifycode").val();
                if (!isMobile(args_mobile)) 
                {
                    tips.html(\'请填写正确的手机号码\');
                    return false;
                }
                
                $.ajax({
                    type: \'POST\',
                    //jiaoyou/index.php?c=ajax&a=checkregmobile
                    // url:"/jiaoyou/index.php?c=ajax",
                    url:"/jiaoyou/usercp.php?c=certify",
                    cache: false,
                    data: {a:"checkregmobile", mobile: args_mobile, verifycode:args_mbverifycode, r: get_rndnum(8)},
                    dataType: \'json\',

                    success: function(data) 
                    {
                        var json = eval(data);

                        var response = json.response;
                        var result = json.msg;
                        // alert(json.response);

                        if (response == "1") 
                        {

                            initGetDownTime(\'mobile\', \'btn_downtime\');/*时间倒计时*/
                            tips.html("<font color=\'green\'>验证码发送成功,请注意查收。</font>");
                        }
                        else 
                        {
                            
                            if (result.length > 0) 
                            {
                                tips.html("<font color=\'red\'>"+result+"</font>");
                            }
                            else 
                            {
                                tips.html("<font color=\'red\'>发送失败,请检查手机号。</font>");
                            }
                        }
                    },
                    
                    error: function() 
                    {
                        tips.html("<font color=\'red\'>请求错误</font>");
                    }
                });
            
            });
        });


        /*----------------- 倒计时 start ----------------*/
        var init_down_time = 60;
        var init_intervalDownTimeObj;

        /**
         * 倒计时
         * @param:: string mbinput 
        */
        function initGetDownTime(mbinput, btnobj) {
            var mb = $("#"+mbinput).val();
            if (isMobile(mb)) {
                init_intervalDownTimeObj = setInterval("countDownTime(\'"+btnobj+"\')", 1000);
            }
        }
        function countDownTime(btn) {
            $(\'#\'+btn).attr("disabled", "true");
            $(\'#\'+btn).val(""+init_down_time+"秒后没收到短信重新发送");
            init_down_time--;
            if (init_down_time == 0){
                clearInterval(init_intervalDownTimeObj); //停止时间
                $(\'#\'+btn).removeAttr("disabled");
                $(\'#\'+btn).val("重新发送");
                init_down_time = 60;
            }
        }
        /*----------------- 倒计时 end ----------------*/
        </script>

      </div>
      <!--//手机认证 End-->

A:

下面php接收ajax接收方法:

 

/*hnb新增加的手机接收验证方法*/
    public function control_checkregmobile( )
    {
        $response = 0;
        $mobile = XRequest::getArgs(\'mobile\');/*得到手机号  这个跟$_post接收数据是一样的*/
        $checkcode = XRequest::getArgs(\'verifycode\');/*得到验证码这个跟$_post接收数据是一样的*/
        
        if (!empty($checkcode)) 
        {
            parent::loadUtil(\'session\');
            $nowcode = XSession::get(\'verifycode\');
            if ($checkcode!== $nowcode) 
            {
                echo json_encode(array(\'response\' => $response,\'msg\'=>\'您的校验码有误!\'));exit;
            }
        }else
        {
            echo json_encode(array(\'response\' => $response,\'msg\'=>\'您的校验码有误!\'));exit;
        }
        
      

        $model = parent::model(\'user\',\'am\');
        $target = "http://api.bjszrk.com/sdk/BatchSend.aspx"; /*接口url*/
        
        if (true === $model->doExistsMobile($mobile)) /*检测手机是否已经验证*/
        {
            $response = 2;
            $msg=\'对不起,您的手机号码已经通过验证,请不要重复操作!\';
        }else 
        {
            $model_certify = parent::model(\'certify\', \'um\');
            list($mbcode, $error) = $model_certify->GetMobileCode($mobile); /*生成一个随机数及插入数据*/
            $content="您的验证码是:".$mbcode."。欢迎注册我主良缘交友网,请勿将验证码告知他人!";
            $msg=$model->postMbCode($mobile, $content);   /*调用post给api接口方法*/ 
            $response = 1;
            $msg=\'验证码已发送成功,请注意查收!\';
        }
        echo json_encode(array(\'response\'=>$response,\'msg\'=>$msg));
    }

 

 

检测手机是否已经验证过的doExistsMobile方法如下:

    public function doExistsMobile($mobile)
    {
        $res = false;
        $sql = \'SELECT `userid` FROM \' . DB_PREFIX . \'user_attr\' . " WHERE `mobile`=\'{$mobile}\'";
        $rows = parent::$obj->fetch_first($sql);
        if (!empty($rows)) {
            $res = true;
        } 
        unset($sql, $rows);
        return $res;
    }
/*GetMobileCode方法具体实现如下:*/


/*r把随机得到的6位验证码insert到数据库表中
*/ public function GetMobileCode($mobile) { $result = 0; $message = null; $checkcode = XHandle::getRndChar(6, 1); $userid=parent::$wrap_user[\'userid\']; $sql="update user_status set mobilesalt=\'$checkcode\' where userid=\'$userid\'"; parent::$obj->query($sql); $result = 1; $sql = ((\'SELECT * FROM \' . DB_PREFIX) . \'mobile_checkcode\') . " WHERE `mobile`=\'{$mobile}\'"; $rows = parent::$obj->fetch_first($sql); if (!empty($rows)) { $array = array(\'checkcode\' => $checkcode, \'updatetime\' => time()); parent::$obj->update(DB_PREFIX . \'mobile_checkcode\', $array, (\'`id`=\\'\' . $rows[\'id\']) . \'\\'\'); } else { $id = parent::$obj->fetch_newid((\'SELECT MAX(id) FROM \' . DB_PREFIX) . \'mobile_checkcode\', 1); $array = array(\'id\' => $id, \'mobile\' => $mobile, \'checkcode\' => $checkcode, \'createtime\' => time()); parent::$obj->insert(DB_PREFIX . \'mobile_checkcode\', $array); } unset($sql); unset($rows); return array($checkcode, $message); }

 

B:

下面是得到了验证码Form表单点提交php的方法.

 

        submit提交
    */
    public function control_rzmobile( )
    {
        $service = parent::service( "certify", "us" );/*接收数据,验证手机格式及号码*/
        list( $mobile, $salt ) = $service->validRzMobile( );/*salt 为手机验证码*/
        unset( $service );
        
        $model = parent::model( "certify", "um" );
        $result = $model->doValidMobile( $mobile, $salt );  /*调用model三张表进行数据操作*/
        unset( $model );
        if ( TRUE === $result )
        {
            
            if ( $this->halttype == "jdbox" )
            {
                XHandle::jqdialog( "手机号码验证成功", 1 );
            }
            else
            {
                XHandle::halt( "手机号码验证成功", $this->ucfile."?c=certify", 0 );
            }
        }
        else
        {
            XHandle::halt( "手机号码验证失败", "", 1 );
        }
    }

 

 

上面dovalidmobile函数方法具体实现:

/*手机认证提交 分别在三个表里操作对象*/
    public function doValidMobile( $mobile, $validkey )
    {
        $result = FALSE;
        $sql = "SELECT userid FROM ".DB_PREFIX.( "user_status WHERE mobilesalt=\'".$validkey."\' AND userid=\'" ).parent::$wrap_user[\'userid\']."\'";
        //SELECT userid FROM user_status WHERE mobilesalt=\'5522\' AND userid=\'209367\'
        $rows = parent::$obj->fetch_first( $sql );
        
        if ( !empty( $rows ) )
        {
            $status_array = array(
                "mobilerz" => 1,
                "mobilesalt" => XHandle::getrndchar( 6, 1 )
                );
            // print_r($status_array);exit;
            parent::$obj->update( DB_PREFIX."user_status", $status_array, "userid=\'".parent::$wrap_user[\'userid\']."\'" );
            $attr_array = array(
                "mobile" => $mobile
                );
            parent::$obj->update( DB_PREFIX."user_attr", $attr_array, "userid=\'".parent::$wrap_user[\'userid\']."\'" );
            parent::loadlib( "user" );
            $star = XUser::updatestar( parent::$wrap_user[\'userid\'] );  /*加星为user_status表里设置star星级*/
            $result = TRUE;
            if ( TRUE === $result )
            {

                $m_indexs = parent::model( "indexs", "am" );  /*作用在user_params表里加上论证标志,可能是用户左边栏加上星标志*/
                $m_indexs->updateIndexs( parent::$wrap_user[\'userid\'], array(
                    "rzmobile" => 1,
                    "star" => $star
                    ) );
                unset( $m_indexs );
            }
        }
        return $result;
    }