WordPress程序添加搜索添加人机验证代码教程

admin CMS教程评论664阅读模式

前言:

WordPress的搜索一直是一个很占内存的功能,如果你的文章很多, 那么执行一次搜索会相对卡顿,那么我们如何尽可能的防范一下呢? 比如机器人扫描到了搜索页面,那将可能直接导致内存爆满mysql进程被终止。

WordPress程序添加搜索添加人机验证代码教程

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' );

如果没有使用第三方的搜索,为WP默认搜索加个验证,还是非常必要的,效果可以看本站搜索。验证过一次后,只有清空浏览器 cookie 才会需要再次验证,本站也是用的这种方法。

文章声明:
1、本站文章来源于互联网,仅供学习交流参考使用,严禁用于商业用途,因此造成的一切法律后果自行承担。
2、本站不对文章内容的完整性和安全性负责,请自行辨别,如发现有问题,请及时联系我们进行处理。
3、如果你有比较好的文章需要发布,可以联系站长屋VPS小编,或者自行点击 投稿。
4、若文章中有侵权或不适当内容,请告知我们,本站会第一时间进行处理。 免责申明。
admin
  • 我们不提供免费技术支持,本文属于用户投稿。
  • 转载请务必保留本文链接:https://www.zzwvps.com/747.html

发表评论