You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将获取Cloudflare国家代码的JS转为PHP,实现表单防垃圾

后台PHP获取Cloudflare国家代码并校验表单提交地区

实现方案

直接在PHP后台请求Cloudflare的trace接口提取国家代码,通过Session存储该值,表单提交时校验是否为美国(US)或加拿大(CA)地区。全程逻辑在后台执行,前端无法看到校验规则,有效避免垃圾发送者绕过。

分步代码实现

1. 页面初始化时获取并存储国家代码

在表单所在页面的顶部添加以下PHP代码,用于请求接口并将国家代码存入Session:

<?php
session_start();

// 仅在Session无国家代码时发起请求,减少重复调用
if (!isset($_SESSION['country_code'])) {
    $trace_url = 'https://www.cloudflare.com/cdn-cgi/trace';
    
    // 优先使用cURL(兼容性更好)
    $ch = curl_init($trace_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $response = curl_exec($ch);
    curl_close($ch);

    // 提取loc字段后的两位国家代码
    preg_match('/loc=([A-Z]{2})/', $response, $matches);
    $_SESSION['country_code'] = isset($matches[1]) ? $matches[1] : '';
}
?>

<!-- 你的表单HTML -->
<form method="post" action="submit.php">
    <!-- 表单字段示例 -->
    <label>姓名:<input type="text" name="name"></label>
    <label>邮箱:<input type="email" name="email"></label>
    <input type="submit" name="submit" value="提交">
</form>

2. 表单提交校验逻辑(submit.php)

创建提交处理脚本,校验Session中的国家代码,区分正常提交和垃圾提交:

<?php
session_start();

// 允许提交的国家代码列表
$allowed_countries = ['US', 'CA'];
$country_code = $_SESSION['country_code'] ?? '';

if (isset($_POST['submit'])) {
    // 校验国家代码是否在允许范围内
    if (!in_array($country_code, $allowed_countries)) {
        // 垃圾提交处理:发送至审核邮箱
        $to = 'audit@yourdomain.com';
        $subject = '[垃圾拦截] 非目标地区表单提交';
        $message = "提交者国家代码: {$country_code}\n";
        $message .= "提交时间: " . date('Y-m-d H:i:s') . "\n";
        $message .= "提交内容:\n" . print_r($_POST, true);
        
        // 发送邮件(可根据实际需求使用PHPMailer等库)
        mail($to, $subject, $message);
        
        die('提交失败,请确认您的地区是否符合要求');
    } else {
        // 正常提交流程:发送至业务邮箱
        $to = 'business@yourdomain.com';
        $subject = '[正常提交] 表单申请';
        $message = "提交者国家代码: {$country_code}\n";
        $message .= "提交时间: " . date('Y-m-d H:i:s') . "\n";
        $message .= "提交内容:\n" . print_r($_POST, true);
        
        mail($to, $subject, $message);
        
        echo '提交成功!我们会尽快与您联系。';
    }
}
?>

注意事项

  • 确保服务器已启用cURL扩展,如果未启用,可替换为file_get_contents(需开启allow_url_fopen)
  • 建议配置Session安全参数(如session.cookie_httponly = On、session.cookie_secure = On),防止会话劫持
  • 若请求Cloudflare接口失败,可添加异常处理逻辑(如默认拒绝提交)
  • 无法完全避免使用美国/加拿大代理的垃圾发送者,但能过滤绝大多数非目标地区的垃圾提交

内容的提问来源于stack exchange,提问作者qwerty321

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:53:14