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

CodeIgniter 3中PHP Curl跨控制器调用遇CSRF 403错误求助

解决CodeIgniter 3中Curl调用内部接口CSRF验证403错误

问题根源

  1. 会话Cookie未传递:CodeIgniter的CSRF验证与用户会话绑定,Curl发起的是独立请求,默认不会携带当前控制器的会话Cookie,导致后端生成新会话,你传递的CSRF令牌和新会话的令牌不匹配,触发403。
  2. Curl配置语法错误:代码中CURLOPT_POST, true,是无效配置项,应使用键值对CURLOPT_POST => true,,这会导致POST请求参数无法正确发送。

解决方案

1. 修复Curl配置并传递会话Cookie

在Curl请求中添加当前会话的Cookie,同时修正语法错误:

修正后的Main控制器代码:

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Main extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // 确保会话已初始化
        $this->load->library('session');
    }
    
    public function checkAjax()
    {
        // 获取当前会话的Cookie(默认CI会话Cookie名为ci_session)
        $session_cookie = 'ci_session=' . $this->input->cookie('ci_session');
        
        $curl = curl_init();
        $post_data = [
            $this->security->get_csrf_token_name() => $this->security->get_csrf_hash(),
            'number' => 3
        ];
        
        curl_setopt_array($curl, [
            CURLOPT_PORT => "8080",
            CURLOPT_URL => "http://localhost:8080/ci/ajax",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_POST => true, // 修正语法错误
            CURLOPT_POSTFIELDS => http_build_query($post_data),
            CURLOPT_COOKIE => $session_cookie, // 传递会话Cookie
            CURLOPT_FOLLOWLOCATION => 1
        ]);

        $response = curl_exec($curl);
        $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo ($httpcode >= 400) ? "Enough" : htmlspecialchars($response);
        }
    }
}

2. 可选:排除特定URL的CSRF验证(仅适用于信任的内部调用)

如果允许内部调用的接口跳过CSRF验证,可在application/config/config.php中配置排除规则:

$config['csrf_exclude_uris'] = array('ajax', 'main/checkAjax');

验证逻辑说明

传递会话Cookie后,后端Ajax控制器会复用当前用户的会话,此时你传递的CSRF令牌与会话中存储的令牌一致,即可通过CSRF验证并正常返回接口数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:05:37