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

CodeIgniter3中回调验证规则validate_captcha找不到的问题求助

CodeIgniter 3 回调验证reCAPTCHA报错:无法找到回调验证规则validate_captcha

调试时出现错误提示:

Unable to find callback validation rule: validate_captcha

问题原因及解决步骤:

  1. 回调函数权限问题
    CodeIgniter的表单验证回调函数必须是公共(public)方法,且与表单验证代码在同一个控制器内。你的validate_captcha函数未声明public,默认是私有方法,框架无法访问。

  2. API请求URL拼接错误
    原代码中URL里多了一个多余的点:.".&response=",这会导致请求参数无效,即使回调能执行,验证也会失败。

  3. 响应处理逻辑错误
    Google返回的是JSON字符串,不能直接用字符串拼接判断success,需要先转成数组再校验。


修正后的完整代码:

控制器中的表单验证部分:

$setting_detail = $this->auth_model->settings_data();

if ($setting_detail[0]['captcha'] == 0 && $setting_detail[0]['secret_key'] != null && $setting_detail[0]['site_key'] != null) {

    $this->form_validation->set_rules('g-recaptcha-response', 'reCAPTCHA验证', 'required|callback_validate_captcha');
    $this->form_validation->set_message('validate_captcha', '请勾选reCAPTCHA验证框');

    if ($this->form_validation->run() == FALSE) {
        $this->session->set_userdata(array('exception' => display('please_enter_valid_captcha')));
        redirect(base_url('login')); // 用框架自带的redirect更规范
    } 
}

修正后的回调函数:

public function validate_captcha() {
    $setting_detail = $this->auth_model->settings_data();
    $captcha = $this->input->post('g-recaptcha-response');
    $secretKey = $setting_detail[0]['secret_key'];
    $remoteIp = $_SERVER['REMOTE_ADDR'];

    // 修正URL拼接错误
    $url = "https://www.google.com/recaptcha/api/siteverify?secret={$secretKey}&response={$captcha}&remoteip={$remoteIp}";
    $response = file_get_contents($url);
    $responseData = json_decode($response, true);

    // 正确校验success字段
    return $responseData['success'] ?? FALSE;
}

额外注意事项:

  • 确保php.ini中allow_url_fopen已开启,否则file_get_contents无法请求外部API;若无法开启,可改用cURL实现请求。
  • 确认控制器已加载form_validation和session库,或在application/config/autoload.php中配置自动加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:50:20