search
HomeBackend DevelopmentPHP TutorialImplementation of SMS verification code sending limit analysis based on PHP

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>

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();  }
}

}
?>

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
This article is reproduced at:jb51. If there is any infringement, please contact admin@php.cn delete
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools