<?php require_once('./Connections/BE2.php'); ?>
<?php
 if (!isset($_SESSION)){ session_start(); }
 
 $err=9;
 $edoc='err';
 
 
 if($err==9){
   mysql_select_db($database_BE2, $BE2);
   $query_Rtd = sprintf("SELECT * FROM register_sms WHERE ssid = '%s' ", session_id());
   $Rtd = mysql_query($query_Rtd, $BE2) or die(mysql_error());
   $row_Rtd = mysql_fetch_assoc($Rtd);
   $totalRows_Rtd = mysql_num_rows($Rtd); 
   if($totalRows_Rtd>5){ $err=2; $edoc='Over Call';}
   mysql_free_result($Rtd);
 }
 if($err==9){
    $difftime=time()-180;	
	$diff2=date('Y-m-d H:i:s');   
    mysql_select_db($database_BE2, $BE2);
    $query_Rtd = sprintf("SELECT * FROM register_sms WHERE iip = '%s' AND itime>='%s'", $_SERVER["REMOTE_ADDR"],$diff2);
    $Rtd = mysql_query($query_Rtd, $BE2) or die(mysql_error());
    $row_Rtd = mysql_fetch_assoc($Rtd);
    $totalRows_Rtd = mysql_num_rows($Rtd); 
    if($totalRows_Rtd>3){ $err=3; $edoc='Over Call ip';}
	mysql_free_result($Rtd);
	}	 
 if($err==9){ 
    
	$mobile=isset($_POST['mobile'])?$_POST['mobile']:'0';
	
	$tmp_passwd=sprintf("%06d",rand(0,999999));
    $message = 'SKYBNI天空商城新會員簡訊通知，您的驗證碼'.$tmp_passwd.' 請於5分鐘內輸入完成,以確保您的權益,天空商城敬上';
	
	mysql_select_db($database_BE2, $BE2);
    $INSERT_Rtd = sprintf("INSERT INTO register_sms (phone,ssid,iip,ipw,itime) VALUES ('%s','%s','%s','%s','%s')",$mobile,session_id(),$_SERVER["REMOTE_ADDR"],$tmp_passwd,date('Y-m-d H:i:s',time()) );
     mysql_query($INSERT_Rtd, $BE2) or die(mysql_error());
 
     $err=9; 
	 $edoc='OK';
	
	 $sms_url= "username=yskin&password=12345123&type=now&encoding=unicode&vldtme=3600&mobile=".$mobile."&message=".$message;

     $msg2 = $sms_url ;
     $num = strlen($msg2);
     $is_send=true;
	 
	 if($is_send){
	 // 打開 API 閘道
     $fp = fsockopen ("api.twsms.com", 80);
     $MSGData='';
     if ($fp) {
       $MSGData = $MSGData."POST /send_sms.php HTTP/1.1\r\n";
       $MSGData = $MSGData."Host: api.twsms.com\r\n";
       $MSGData = $MSGData."User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)\r\n";
       $MSGData = $MSGData."Content-Length: ".$num."\r\n";
       $MSGData=$MSGData."Content-Type: application/x-www-form-urlencoded\r\n";
       $MSGData = $MSGData."Connection: Close\r\n\r\n";
       $MSGData = $MSGData.$msg2."\r\n";
       fputs ($fp, $MSGData);

       // 取出回傳值
        while (!feof($fp)) $Tmp[]=fgets ($fp,128); 

       // 關閉閘道
        fclose ($fp);

       // 顯示回傳值
     }
	 // API OFF
	  }
 }

$result = array();
$result['err'] = $err;
$result['edoc'] = $edoc;
 
echo json_encode($result);
  

?>
