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

在CodeIgniter 3辅助函数中获取file_get_contents的HTTP状态码

解决CodeIgniter 3中辅助函数获取API状态码的问题

问题核心在于file_get_contents默认不会处理HTTP错误状态码(比如400、500),遇到这类情况会直接抛出PHP警告,同时你也没法直接拿到API返回的真实状态码。我们可以通过改造辅助函数,主动获取并解析响应头里的状态码,再把状态码和响应数据一起返回给控制器处理。

方案1:基于file_get_contents改造辅助函数

直接给file_get_contents添加上下文选项,忽略HTTP错误并获取响应头,然后解析状态码:

function get_json($url) {
    // 创建HTTP请求上下文,忽略错误并指定接收JSON格式
    $context = stream_context_create([
        'http' => [
            'ignore_errors' => true, // 关键:不让PHP直接抛出HTTP错误
            'header' => 'Accept: application/json'
        ]
    ]);

    // 获取API响应内容
    $response = file_get_contents($url, false, $context);
    
    // 解析响应头中的状态码(PHP自动填充$http_response_header变量)
    $status_code = 200; // 默认成功状态
    foreach ($http_response_header as $header) {
        if (str_starts_with($header, 'HTTP/')) {
            $status_parts = explode(' ', $header);
            $status_code = (int)$status_parts[1];
            break;
        }
    }

    // 根据状态码返回结构化结果
    if ($status_code >= 200 && $status_code < 300) {
        // 成功响应:解析JSON数据
        $data = json_decode($response, true);
        return [
            'status' => $status_code,
            'data' => $data,
            'error' => null
        ];
    } else {
        // 错误响应:返回状态码和错误信息(兼容API返回非JSON的情况)
        $error_data = json_decode($response, true) ?? ['message' => 'API请求失败'];
        return [
            'status' => $status_code,
            'data' => null,
            'error' => $error_data
        ];
    }
}

方案2:用cURL替代file_get_contents(更推荐生产环境)

cURL在处理HTTP请求和错误时更灵活,支持超时、重试等配置,稳定性更高:

function get_json($url) {
    $ch = curl_init($url);
    
    // 设置cURL选项
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应内容而非直接输出
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置超时时间,避免挂起
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 自动跟随重定向

    // 执行请求并获取结果
    $response = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 直接获取状态码
    $curl_error = curl_error($ch);
    
    curl_close($ch);

    // 处理cURL自身的错误
    if ($curl_error) {
        return [
            'status' => 500,
            'data' => null,
            'error' => ['message' => 'API请求异常: ' . $curl_error]
        ];
    }

    // 处理API返回的状态码
    if ($status_code >= 200 && $status_code < 300) {
        $data = json_decode($response, true);
        return [
            'status' => $status_code,
            'data' => $data,
            'error' => null
        ];
    } else {
        $error_data = json_decode($response, true) ?? ['message' => 'API返回错误响应'];
        return [
            'status' => $status_code,
            'data' => null,
            'error' => $error_data
        ];
    }
}

控制器和视图的适配处理

改造辅助函数后,控制器可以拿到状态码和数据,再传递给视图:

控制器代码示例

public function load_table() {
    $api_url = '你的API地址';
    $api_result = get_json($api_url);

    // 根据状态码处理页面逻辑
    if ($api_result['status'] === 200) {
        $view_data['table_data'] = $api_result['data'];
        $view_data['error'] = null;
    } else {
        $view_data['table_data'] = [];
        $view_data['error'] = $api_result['error'];
        // 把API状态码传递给前端(可选)
        http_response_code($api_result['status']);
    }

    $this->load->view('your_table_view', $view_data);
}

视图代码示例

<?php if (!empty($error)): ?>
    <div class="alert alert-danger">
        <p>错误状态码: <?php echo http_response_code(); ?></p>
        <p>错误信息: <?php echo $error['message']; ?></p>
    </div>
<?php else: ?>
    <!-- 渲染数据表格 -->
    <table class="table">
        <thead>
            <!-- 表头 -->
        </thead>
        <tbody>
            <?php foreach ($table_data as $row): ?>
                <tr>
                    <!-- 表格内容 -->
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

这样改造后,不仅能避免PHP错误抛出,还能让视图准确获取到API的真实状态码,实现友好的错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:47:23