Home Backend Development PHP Tutorial Implementation of SMS verification code sending limit analysis based on PHP

Implementation of SMS verification code sending limit analysis based on PHP

Jul 13, 2020 pm 05:30 PM
php send SMS verification code limit

Implementation of SMS verification code sending limit analysis based on PHP

Restrict the mobile phone number, IP, and browser (using a unique identifier) ​​for users to obtain SMS verification codes. The method introduced in this article is that users can only obtain verification codes 10 times a day through the same browser or the same IP address, or can only obtain SMS verification codes 3 times with the same mobile phone number. The three restrictions are in an "or" relationship. If one exceeds the limit, it will Send verification code. The method is to record and write the user's mobile phone number, ip, ur_r on the server side to a file, and then determine the number of times the user requests to send a verification code by reading the file record to limit the number. . The method is as follows:

Get the SMS verification code page:

<!DOCTYPE html>
<html>
<head></head>
<body>
<!-- 隐藏表单uv_r标识,用于对获取验证码的浏览器进行限制,唯一标识存储于浏览器cookie中。在用户进行获取短信验证码操作时将标识传入后台代码(可以通过js传入后台,此处未提供js代码) -->
<input type="hidden" name="uv_r" value="" id="uv_r">
</body>
<script type=”text/javascript”>
/*
使用js获取cookie中ur_r唯一标识,如果不存在,生成唯一标识,js写入cookie,并将唯一标识赋给隐藏表单。
*/
 //唯一标识存入cookie
    var _uuid = getUUID();
    if(getCookie("_UUID_UV")!=null && getCookie("_UUID_UV")!=undefined)
    {
      _uuid = getCookie("_UUID_UV");
    }else{
      setCookie("_UUID_UV",_uuid);
    }
    document.getElementById("uv_r").value = _uuid;//赋给hidden表单
    //生成唯一标识
    function getUUID()
    {
      var uuid = new Date().getTime();
      var randomNum =parseInt(Math.random()*1000);
      return uuid+randomNum.toString();
    }
    //写cookie
    function setCookie(name,value)
    {
      var Days = 365;//这里设置cookie存在时间为一年
      var exp = new Date();
      exp.setTime(exp.getTime() + Days*24*60*60*1000);
      document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    }
    //获取cookie
    function getCookie(name)
    {
      var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
      if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
      else
        return null;
    }
</script>
</html>
Copy after login

Back-end PHP processing code:

<?php
Class regMod{
//定义全局变量,用于设置记录文件的路径
Protected $Root = null;
Public function __construct(){
$this -> Root = APP_PATH."/data/msg_logs/";//自己定义的文件存放位置
}
//获取短信验证码操作(Ajax方法为好)
Public function get_authentication_code(){
if ($_POST[&#39;uv_r&#39;] && $_POST[&#39;tel&#39;]) {
$ip=$_SERVER["REMOTE_ADDR"];//ip
  $tel = $_POST[&#39;tel&#39;];//电话
  $uv_r = $_POST[&#39;uv_r&#39;];//ur_r标识
  if(empty($uv_r)){
    $uv_r = 0;
  }
}

      //判断数据是否超过了限制
$uvr_num = $this->checkUvr($uv_r);
$tel_num = $this->checkTel($tel);
$ip_num = $this->checkIp($ip);

if ($uvr_num < 10 && $tel_num < 4 && $ip_num < 10) {
Echo "发送验证码";//符合发送条件,发送验证码的操作
} else {
Echo “不发送验证码”;
//当不发送验证码时,将数据存入文件,用于方便查询
$data = $tel . "|" . $ip . "|" . $uv_r . "|";
  if ($uv_r>0 && $uvr_num >= 10) {
    $data = $data . "A@";
  }
  if ($tel_num >= 4) {
    $data = $data . "B@";
  }
  if ($ip_num >= 10) {
    $data = $data . "C@";
  }
  $this->wirteFile("", $data);
  $this->ajax_return(0, "您今日获取短信验证码的次数过多!");//给用户返回信息,ajax_return()为自写方法(未提供)
  }
}
//以下方法为私有方法
//检测ur_r在文件中出现的次数
Private function checkUvr($data){
  $fileName = "Uv_".date("Ymd",time()).".dat";
  $filePath = ($this -> Root).$fileName;//组装要写入的文件的路径
  $c_sum = 0;
  if(file_exists($filePath)){//文件存在获取次数并将此次请求的数据写入
    $arr=file_get_contents($filePath);
    $row=explode("|",$arr);
    $countArr=array_count_values($row);
    $c_sum = $countArr[$data];
    if($c_sum<10)
    {
      $this -> wirteFile($filePath,$data."|");
    }
    return $c_sum;
  }else{//文件不存在创建文件并写入本次数据,返回次数0
    $this -> wirteFile($filePath,$data."|");
    return $c_sum;
  }
}
//检测Tel在文件中出现的次数
Private function checkTel($data){
  $fileName = "Tel_".date("Ymd",time()).".dat";
  $filePath = ($this -> Root).$fileName;
  $c_sum = 0;
  if(file_exists($filePath)){
    $arr=file_get_contents($filePath);
    $row=explode("|",$arr);
    $countArr=array_count_values($row);
    $c_sum = $countArr[$data];
    if($c_sum<4)
    {
      $this -> wirteFile($filePath,$data."|");
    }
    return $c_sum;
  }else{
    $this -> wirteFile($filePath,$data."|");
    return $c_sum;
  }
}
//检测IP在文件中存在的次数
Private function checkIp($data){
  $fileName = "Ip_".date("Ymd",time()).".dat";
  $filePath = ($this -> Root).$fileName;
  $c_sum = 0;
  if(file_exists($filePath)){
    $arr=file_get_contents($filePath);
    $row=explode("|",$arr);
    $countArr=array_count_values($row);
    $c_sum = $countArr[$data];
    if($c_sum<10)
    {
      $this -> wirteFile($filePath,$data."|");
    }
    return $c_sum;
  }else{
    $this -> wirteFile($filePath,$data."|");
    return $c_sum;
  }
}
/**
* 将数据写入本地文件
* @param $filePath 要写入文件的路径
* @param $data 写入的数据
*/
Private function wirteFile($filePath,$data){
try {
    if(!is_dir($this->Root)){//判断文件所在目录是否存在,不存在就创建
      mkdir($this->Root, 0777, true);
    }
    if($filePath==""){//此处是不发送验证码时,记录日志创建的文件
      $filePath = ($this -> Root)."N".date("Ymd",time()).".dat";
    }
//写入文件操作
    $fp=fopen($filePath,"a+");//得到指针
    fwrite($fp,$data);//写
    fclose($fp);//关闭
  } catch (Exception $e) { print $e->getMessage();  }
}

}
?>
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study .

Related learning recommendations: PHP programming from entry to proficiency

The above is the detailed content of Implementation of SMS verification code sending limit analysis based on PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles