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

如何在PHP的cURL自定义函数file_get_contents_curl中获取响应状态码?

获取HTTP状态码并处理429限流的PHP cURL函数实现

你可以通过curl_getinfo()函数配合CURLINFO_HTTP_CODE选项获取HTTP响应状态码,以下是修改后的file_get_contents_curl函数,集成状态码检测和429限流处理逻辑:

function file_get_contents_curl($url) {
    $ch = curl_init();

    // 基础cURL配置
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
    // 可根据需求添加超时、SSL验证等其他配置

    $response = curl_exec($ch);
    
    // 获取HTTP响应状态码
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    // 检测429状态码,触发休眠逻辑
    if ($httpcode === 429) {
        sleep(5);
        // 可选:休眠后自动重新请求(根据业务需求开启)
        // return file_get_contents_curl($url);
    }

    // 返回响应内容与状态码,方便外部处理
    return [
        'content' => $response,
        'httpcode' => $httpcode
    ];
}

调用示例

$apiResult = file_get_contents_curl('https://your-api-url.com');
$httpStatus = $apiResult['httpcode'];
$jsonContent = $apiResult['content'];

// 解析JSON响应
if ($jsonContent) {
    $data = json_decode($jsonContent, true);
}

// 外部也可基于状态码做额外处理
if ($httpStatus === 429) {
    // 比如记录日志、二次重试等
}

可选写法:通过引用参数传递状态码

如果不需要返回数组,也可以用引用参数单独传递状态码:

function file_get_contents_curl($url, &$httpcode) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    
    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);

    if ($httpcode === 429) {
        sleep(5);
    }

    return $response;
}

调用方式:

$statusCode = 0;
$jsonContent = file_get_contents_curl('https://your-api-url.com', $statusCode);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:55:23