search
HomeBackend DevelopmentPHP TutorialPHP+JavaScript implements refresh button to continue countdown

场景:发送一个验证码到手机,当验证码发出时,会提示隔 1 分钟之后可以再次发送。通常有这几种方式防止恶意请求,一是再次发送之前需要输入验证码,二是在指定的时间间隔之内不能再次发送。

推荐:《PHP视频教程

有些网站在 1 分钟的间隔之间之内发送按钮的确是禁用了,但是只要刷新浏览器,或者通过 F12 工具修改 Button 的 disabled 属性,在时间间隔之内仍然可以点击按钮。

需要在刷新的情况下仍然保持倒计时,可以在服务器端用过 SESSION 记录点击的时间,并且每次加载页面的时候都去检测当前时间和点击时间的时间差。

测试框架使用 ThinkPHP 3.2.3

视图文件位于:/Application/Home/View/Mail/index.html

控制器位于:/Application/Home/Controller/MailController.class.php

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
</head>
<body>
	<input type="button" value="发送验证码" id="send">
</body>
<script>

	$i = 30; // 倒计时的秒数

	// 检测剩余时间
  $(function(){
  	$.ajax({
			url: "{:U(&#39;Home/Mail/send_time&#39;, &#39;&#39;, &#39;&#39;)}",
			method: &#39;post&#39;,
			data: {
				&#39;seconds&#39;: $i
			},
			success: function(data) {
				console.log(data);
				if(data > 0) {
					interval(data);
				}
			}
  	});
  });

  // 发送点击时间
	$("#send").click(function(){

		$.ajax({
			url: "{:U(&#39;Home/Mail/record_time&#39;, &#39;&#39;, &#39;&#39;)}",
			method: &#39;post&#39;,
			data: {
				&#39;seconds&#39;: $i,
				&#39;click_time&#39;: parseInt(new Date().getTime()/1000)
			},
			success: function(data) {
				if(data != 0) { // 防止通过 F12 修改 button 的 disabled 属性在间隔时间之内再次点击按钮
					interval($i);
				}
				console.log(data);
			}
		});
	});

	// 显示提示文字,禁用提交按钮
	function setTime($t) {
		$button = $("#send");

		$message = $("<span id=&#39;message&#39;> <span id=&#39;wait&#39;>"+ $t +"</span>秒后可重新发送验证码...</span>");
		$message.insertAfter($button);
		$button.attr("disabled", true);	
	}

	// 倒计时
	function interval($t) {
		setTime($t);
		var wait = document.getElementById(&#39;wait&#39;);
		var interval = setInterval(function(){
			var time = --wait.innerHTML;
			if(time <= 0) {
				clearInterval(interval);
				$button.attr("disabled", false);
				$message.remove();	
			};
		}, 1000);		
	}

</script>
</html>

 MailController.class.php:

<?php

namespace Home\\\\Controller;
use Think\\\\Controller;

class MailController extends Controller {

	public function index() {
		$this->display();
	}

	// 记录时间戳
	public function record_time() {

		session_start();

		if(IS_AJAX) {
			$click_time = $_POST[&#39;click_time&#39;];
			if(isset($_SESSION[&#39;click_time&#39;]) && $click_time - $_SESSION[&#39;click_time&#39;] < $_POST[&#39;seconds&#39;]) {
				echo 0; // 防止通过 F12 修改 button 的 disabled 属性在间隔时间之内再次点击按钮
			} else {
				$_SESSION[&#39;click_time&#39;] = $click_time;
				echo date(&#39;Y-m-d H:i:s&#39;, $click_time);
			}
		}
	}

	// 发送时间戳
	public function send_time() {

		session_start();

		$time_diff = time() - $_SESSION[&#39;click_time&#39;];

		if(isset($_SESSION[&#39;click_time&#39;]) && $time_diff < 30) {
			$diff = $_POST[&#39;seconds&#39;] - $time_diff;
			if($diff > 0) {
				echo $_POST[&#39;seconds&#39;] - $time_diff;
			} else {
				echo 0;
			}
			
		} else {
			unset($_SESSION[&#39;click_time&#39;]);
		}
	}
}

实现效果图

初始状态:

 点击按钮:

console 中显示的时间戳是点击按钮时的时间戳,通过 AJAX 发送到服务器端并且记录在 SESSION 中

倒计时结束之前刷新页面:

console 控制台显示的 12 表示距离倒计时结束还有 12 秒,通过加载页面时的 AJAX 请求服务器,比较当前时间和 SESSION 中记录的点击时间(如果有)并且两者相差的时间小于倒计时的时间,则返回剩余的时间,客户端接受到时间后仍然保持按钮禁用,同时从返回的时间开始倒计时。

倒计时结束:

按钮恢复可用。

在倒计时间隔时间内通过 F12 删除 button 的 disabled 属性,虽然按钮可以点击,但是由于返回值是 0,因此不会触发新的动作以及重新计时:

 删除属性之前:

The above is the detailed content of PHP+JavaScript implements refresh button to continue countdown. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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 Article

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools