PHP实现短信验证码

手机验证码流程:


获取手机验证码事件:正则验证手机号,将手机号码和验证码作为参数异步访问手机验证码ajax页面


手机验证码ajax页面:验证验证码,生成手机验证码,生成流水号,引用接口页面发送验证码,如果成功则将验证码信息写入数据库


注册按钮事件:将手机号和手机验证码作为参数传入注册ajax页面


注册ajax页面:判断手机验证码是否正确,判断会员是否重复,将用户信息写入数据库


总之,验证完验证码就发送手机验证码,之后只验证手机验证码


//手机验证码ajax页面
if($p['act']=="telcode"){
    //验证验证码
    $code = trim($p['code']);
    if($code!=$_SESSION["login_check_num"]){
        echo "codeHad";
    }else{
    
        //手机号
        $tel = trim($p['tel']);
        
        //生成手机验证码
        $code = "";
        for($i=0;$i<4;$i++){
            $code .= rand(0,9);
        }
        
        //流水号
    	list($usec, $sec) = explode(" ", microtime());
    	$time = (float)$usec + (float)$sec;
    	
    	
        //发送验证码
        $sendSms->SpCode = '';//企业编号
        $sendSms->LoginName = '';//用户名称
        $sendSms->Password = '';//用户密码
        $sendSms->MessageContent = '您的验证码为'.$code;//短信内容
        $sendSms->UserNumber = $tel;//手机号码
        $sendSms->SerialNumber = $time;//回执流水号,时间格式精确到毫秒
        $sendSms->ScheduleTime = '';//空为立即发送
        $sendSms->ExtendAccessNum = '';//检测方式参数
        $res = $sendSms->send();//send方法,返回布尔值
        //如果发送成功则写入数据库
        if($res){
            $sql = "INSERT INTO #__telcode
            SET tel = '$tel',
            code = '$code',
            time = '$time'";
            $db_my->query ($sql);
            echo 'success';
        }else{
            echo 'smsHad';
        }
        
        
        return;
    }
}


//注册ajax页面
if($p['act']=="reg_oa"){
		$username=trim($p['username']);
		$userpwd=trim($p['password']);
		$reg_rand = trim($p['reg_rand']); 
		$group_id=trim($p['group_id']); 
		$tel=trim($p['tel']); //手机号码
		$reg_tel = trim($p['reg_tel']);//获取手机验证码
        $uuid=str_replace('{','',guid());
        $uuid=str_replace('}','',$uuid);
        $uuid=str_replace('-','',$uuid);
        
        
        
		$memberoacunzai=$db_my->get_row("select * from  t_s_base_user WHERE username='".$username."'");
		//判断手机验证码是否正确
		$telcodecheck=$db_my->get_row("select * from #__telcode WHERE tel='".$tel."' order by id desc limit 1");
		$telcode = $telcodecheck->code;
		
		if($reg_rand!=$_SESSION["login_check_num"]){
		echo "codeHad";
		}		
		elseif ($telcode!=$reg_tel){
		echo "telcodeHad";
		}
		elseif (count($memberoacunzai) == 1){
		echo "nameHad";
		}
		
		else{
		
	
		   $sql = "INSERT INTO t_s_base_user
						SET ID = '$uuid',
							username = '$username',
							usertype  = '$group_id',
							password = '".md5($userpwd)."'";
		    $db_my->query ($sql);
		

		  	$memberoa=$db_my->get_row("select * from  t_s_base_user WHERE username='".$username."'");

		
			$sql = "SELECT * FROM pms_owner_info WHERE userid = '".$memberoa->ID."'";
	        $memberoa_o = $db_my->get_row($sql);

		      //记录登录
		
			  ///登录的时候判断商城会员表是否有该会员记录,没有则写入一条记录
			  $membercunzai=$db_my->get_row("select * from  #__member WHERE userid='".$memberoa->ID."'");
			
			  
			  if(count($membercunzai)==1)
			  {
			  $_SESSION['memberoa'] = $memberoa;
			  $_SESSION['memberauth_id'] = $membercunzai->uid;
			  $_SESSION['member'] = $membercunzai;
			  }
			  else{
			  $sql = "INSERT INTO #__member
					  SET uid = NULL,
						  username = '$username',
						  group_id = '".$memberoa->usertype ."',
						  realname = '".$memberoa_o->cowername."',
						  password = '".md5($userpwd)."',
						  email = '$email',
						  tel = '".$tel ."',
						  userid = '".$memberoa->ID."',
						  reg_ip = '" . remote_addr() . "',
						  reg_time = UNIX_TIMESTAMP() ";
			  $db_my->query ($sql);
			  
			  
			  
			 //注册会员,发放100积分。
		    //更新会员帐号当前积分
			 //reg_integral($username,100);

			  
			  
			  $_SESSION['memberoa'] = $memberoa;
			  $membercunzai=$db_my->get_row("select * from  #__member WHERE userid='".$memberoa->ID."'");
			  $_SESSION['memberauth_id'] = $membercunzai->uid;
			  $_SESSION['member'] = $membercunzai;
			  
			  }

   
			 echo "success";
		}
		
		return;
}

//timer处理方法
var InterValObj; //timer变量
var count = 10; //间隔时间
var curCount;//当前剩余秒数
function SetRemainTime() {
    if (curCount == 0) {                
        window.clearInterval(InterValObj);//停止计时器
        $("#telreg").removeAttr("disabled");//启用按钮
        $("#telreg").val("重新发送验证码");
    }
    else {
        curCount--;
        $("#telreg").val("请输入验证码" + curCount);
    }
}


//获取手机验证码事件
function gettelcode(){
	
	
    
    //获取短信验证码按钮事件:验证验证码,验证手机号码,手机号作为参数访问接口页面,异步将手机号和验证码存入数据库中
	var $tel=$("#tel").val();
	var $code=$("#reg_rand").val();
	
	//验证手机号码
	if ($.trim($tel)==''){
		showtip("请输入手机号!");
		$("#tel").focus();
		return false;
	}
	var TelFont= /^1[3|4|5|8][0-9]\d{4,8}$/;
	if($.trim($tel)!=''&&!TelFont.test($.trim($tel))){
		showtip("手机号码格式错误,请重新输入!");
		$("#tel").focus();
		return false;
	}


//手机号码和验证码作为参数访问ajax页面
	$.ajax({
		type: "POST",
		url: ajaxurl+"ajax.php",
		data: "act=telcode&tel="+$tel+"&code="+$code,
		success: function(msg){
				alert(msg);
	            if(msg.replace(/[\r\n]/g,'')=='codeHad')showtip('验证码错误!');
	            if(msg.replace(/[\r\n]/g,'')=='smsHad')showtip('验证码发送失败!');
				if(msg.replace(/[\r\n]/g,'')=='success'){
				showtip('验证码发送成功!');
				//成功发送之后设置间隔
				curCount = count;
			    $("#telreg").attr("disabled", "true");
			    $("#telreg").val("请在" + curCount + "秒内输入验证码");
			    InterValObj = window.setInterval("SetRemainTime()", 1000); //启动计时器,1秒执行一次
				}
			}
			
	});
	
	
	
}


//注册按钮事件
function checkreg_oa() 
{

    var $username=$("#username").val();
	var $password =$("#password").val();
	var $password1 =$("#password1").val();
	var $reg_rand =$("#reg_rand").val();
	var $group_id =$("#group_id").val();
	var $url =$("#url").val();
	var $tel = $("#tel").val();//手机号码
	var $reg_tel = $("#reg_tel").val();//手机验证码

		if ($.trim($username)==''){
		showtip("请输入您的注册账号!");
		$("#username").focus();
		return false;
		}
		
		if(getByteLen($.trim($username))<4 || getByteLen($.trim($username))>20)
		{
		showtip("注册帐号格式错误!");
		$("#username").focus();
		return false;
		}
		
		if ($.trim($password)==''){
		showtip("请输入密码!");
		$("#password").focus();
		return false;
		}
				
		if ($.trim($password1)==''){
		showtip("请确认密码!");
		$("#password1").focus();
		return false;
		}
		
		if ($.trim($password1)!=$.trim($password)){
		showtip("两次输入的密码不一致,请重新输入!");
		$("#password1").focus();
		return false;
		}
		
		if ($.trim($reg_rand)==''){
		showtip("请输入验证码!");
		$("#reg_rand").focus();
		return false;
		}
		
		if ($.trim($tel)==''){
		showtip("请输入手机号!");
		$("#tel").focus();
		return false;
		}
		
		if ($.trim($reg_tel)==''){
		showtip("请输入您手机上的验证码!");
		$("#reg_tel").focus();
		return false;
		}
		
	 //传入手机验证码reg_tel手机号tel
    $.ajax({
        type: "POST",
        url: ajaxurl+"ajax.php",
        data: "act=reg_oa&tel=" + $tel + "&username=" + $username + "®_tel=" + $reg_tel + "&group_id=" + $group_id + "&password=" + $password +"®_rand=" + $reg_rand +"&time="+new Date().toString(),
        success: function (msg) {
			alert(msg);
            if(msg.replace(/[\r\n]/g,'')=='telcodeHad')showtip('手机验证码错误!');
            if(msg.replace(/[\r\n]/g,'')=='nameHad')showtip('用户名已经存在!');
			if(msg.replace(/[\r\n]/g,'')=='success'){showtip('注册成功!');window.location.href=$url;}//
   		}
	});
}


//接口页面
SpCode = '123456';
 * $sendSms->LoginName = 'abc123';
 * $sendSms->Password = '123abc';
 * $sendSms->MessageContent = '测试短信';
 * $sendSms->UserNumber = '15012345678,13812345678';
 * $sendSms->SerialNumber = '';
 * $sendSms->ScheduleTime = '';
 * $sendSms->ExtendAccessNum = '';
 * $sendSms->f = '';
 * $res = $sendSms->send();
 * echo $res ? '发送成功' : $sendSms->errorMsg;
 * 
 */
class SendSmsHttp {
	private $_apiUrl = 'http://gd.ums86.com:8899/sms/Api/Send.do'; // 发送短信接口地址
	public $SpCode;
	public $LoginName;
	public $Password;
	public $MessageContent;
	public $UserNumber;
	public $SerialNumber;
	public $ScheduleTime;
	public $ExtendAccessNum;
	public $f;
	public $errorMsg;
	
	/**
	 * 发送短信
	 * @return boolean
	 */
	public function send() {
		$params = array(
				"SpCode" => $this->SpCode,
				"LoginName" => $this->LoginName,
				"Password" => $this->Password,
				"MessageContent" => iconv("UTF-8", "GB2312//IGNORE", $this->MessageContent),
				"UserNumber" => $this->UserNumber,
				"SerialNumber" => $this->SerialNumber,
				"ScheduleTime" => $this->ScheduleTime,
				"ExtendAccessNum" => $this->ExtendAccessNum,
				"f" => $this->f,
		);
		$data = http_build_query($params);
		$res = iconv('GB2312', 'UTF-8//IGNORE', $this->_httpClient($data));
		$resArr = array();
        parse_str($res, $resArr);
	
		if (!empty($resArr) && $resArr["result"] == 0) return true;
		else {
			if (empty($this->errorMsg)) $this->errorMsg = isset($resArr["description"]) ? $resArr["description"] : '未知错误';
			return false;
		}
	}
	
	
	/**
	 * POST方式访问接口
	 * @param string $data
	 * @return mixed
	 */
	private function _httpClient($data) {
		try {
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,$this->_apiUrl);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			$res = curl_exec($ch);
			curl_close($ch);
			return $res;
		} catch (Exception $e) {
			$this->errorMsg = $e->getMessage();
			return false;
		}
	}
	
	
}
$sendSms = new SendSmsHttp;


你可能感兴趣的:(PHP)