WordPress 如何给搜索页面展示结果前加一个人机验证码?

WordPress的搜索一直是一个很占内存的功能,如果你的文章很多,那么执行一次搜索会相对卡顿,那么我们如何尽可能的防范一下呢?比如机器人扫描到了搜索页面,那将可能直接导致内存爆满mysql进程被终止。这里,我们可以加一个搜索验证码,用户在第一次搜索时需要进行简单的人机验证。一来这样可以有效防止恶意扫描导致内存崩溃,二来可以防止恶意请求关键字生成结果页面。模板兔写了一个简单的验证机制,可将下面代码加到主题的functions.php里即可。

/*
Plugin Name: 搜索验证码
Description: WordPress 搜索验证码
Version: 1.0
Author: 痴痴资讯网
Author URI: https://www.chichizixun.com
*/
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' );

 

版权声明:本站部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如本站内容侵犯了您的权益请联系我们,邮箱:1511977125@qq.com 我们核实后会及时处理,发布内容不代表痴痴资讯网立场,本文标题:WordPress 如何给搜索页面展示结果前加一个人机验证码?本文链接:https://www.chichizixun.com/1102.html