WordPress教程 为搜索添加人机验证 纯代码实现

2024-10-07 0 524

前言:

WordPress 的内置搜索功能在处理大量文章时可能会消耗大量内存,导致页面响应缓慢,甚至可能因为内存溢出而使 MySQL 进程崩溃。为了防止这种情况发生,我们可以采取一些措施来优化搜索体验。

一种有效的方法是在 WordPress 的搜索功能中集成人机验证机制。这样,当用户首次进行搜索时,系统会要求他们完成一个简单的验证步骤。这种方法不仅可以防止恶意扫描攻击导致服务器资源耗尽,还可以减少恶意用户通过搜索关键词生成大量结果页面的行为。

为了实现这一功能,你可以将以下代码添加到你的主题的`functions.php`文件中:


function esc_search_captcha( $query, $error = true ) {
	if ( is_search() && !is_admin() ) {
		if ( ! isset( $_COOKIE['esc_search_captcha'] ) ) {
			$query->is_search = false;
			$query->query_vars['s'] = false;
			$query->query['s'] = false;
 
			if ( $error == true ){
				//$query->is_404 = true;
				if ( isset( $_POST['result'] ) ) {
					if ( $_POST['result'] == $_COOKIE['result'] ) {
						$_COOKIE['esc_search_captcha'] = 1;
						setcookie('esc_search_captcha',1,0,'/');
						echo '<script>location.reload();</script>';
					}
				}
 
				$num1 = rand(1,50);
				$num2 = rand(1,50);
				$result = $num1+$num2;
				$_COOKIE['result'] = $result;
				setcookie('result',urldecode($result),0,'/');
				?>
 
				<html>
				<head>
				<meta charset="UTF-8">
				<title>人机验证</title>
				<style>
				body{color: #333;text-align: center;font-size: 16px;}
				.erphp-search-captcha{margin: 50px auto 15px;max-width: 250px;width: 100%;padding: 40px 20px;border: 1px solid #ddd;text-align: center;border-radius: 5px;}
				.erphp-search-captcha form{margin: 0}
				.erphp-search-captcha input{border: none;border-bottom: 1px solid #666;width: 50px;text-align: center;font-size: 16px;}
				.erphp-search-captcha input:focus{outline: none;}
				.erphp-search-captcha button{border: none;background: transparent;color: #ff5f33;cursor: pointer;}
				.erphp-search-captcha button:focus{outline: none;}
				a{color: #000;font-size: 12px;}
				</style>
				</head>
				<body>
				<div class="erphp-search-captcha">
				<form action="" method="post"><?php echo $num1;?> + <?php echo $num2;?> = <input type="text" name="result" required /> <button type="submit">验证</button></form>
				</div>
				<a href="<?php echo home_url();?>">返回首页</a>
				</body>
				</html>
				<?php
				exit;
			}
		}
	}
}
add_action( 'parse_query', 'esc_search_captcha' );

本文章已结束,如转载请注明:汇站网 » WordPress 教程 为搜索添加人机验证 纯代码实现

收藏 (0)

微信支付 微信扫一扫

支付宝支付 支付宝扫一扫

打赏二维码
点赞 (0)

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

联系官方客服

为您解决烦忧 - 24小时在线 专业服务