WordPress搜索结果页面人机验证:算术验证代码实现
对于开放搜索接口的网站,不法分子可以通过“搜索”方式进行攻击。这种情况不仅限于WordPress,其他内容管理系统(CMS)和自定义网站同样可能面临类似的威胁,轻则导致服务器瘫痪,重则使网站被封禁。

代码添加方法
- 进入WordPress后台
- 点击“外观”
- 选择“主题编辑器”
- 找到并点击
functions.php - 将代码粘贴到文件内容中
- 点击“更新文件”保存更改
代码说明
代码中的 $num1 = rand(1,50); $num2 = rand(1,50); 部分可以调整为更简单的范围,例如将数字范围改为1到5。
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 ) { 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' );

浙公网安备 33010602011771号