萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP file_get_contents 讀取遠端資料超時解決方案

問題背景

網路狀況不佳時,file_get_contents() 讀取遠端 URL 常發生超時或失敗,預設無超時控制,導致腳本卡死。

解決方案:Stream Context 設定超時

<?php
$url = 'https://www.example.com/api/data';

$opts = array(
    'http' => array(
        'method' => "GET",
        'timeout' => 5,          // 總超時秒數(含連線+傳輸)
        'connect_timeout' => 3,  // 連線階段超時(PHP 5.6+)
    )
);

$context = stream_context_create($opts);

// @ 抑制警告,配合錯誤處理
$contents = @file_get_contents($url, false, $context);

if ($contents === false) {
    $error = error_get_last();
    // 記錄日誌、重試、降級處理
    error_log("HTTP request failed: " . $error['message']);
    // 重試邏輯...
} else {
    $data = json_decode($contents, true);
    // 處理資料...
}

進階:重試機制封裝

<?php
function httpGetWithRetry($url, $maxRetries = 3, $timeout = 5, $backoff = 100000) {
    $opts = array(
        'http' => array(
            'method' => 'GET',
            'timeout' => $timeout,
            'connect_timeout' => min(3, $timeout),
            'ignore_errors' => true, // 獲取非 2xx 回應體
        )
    );
    $context = stream_context_create($opts);
    
    for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
        $response = @file_get_contents($url, false, $context);
        
        // 獲取 HTTP 狀態碼
        $httpCode = 0;
        if (isset($http_response_header[0])) {
            preg_match('/\d{3}/', $http_response_header[0], $matches);
            $httpCode = (int)$matches[0];
        }
        
        if ($response !== false && $httpCode >= 200 && $httpCode < 300) {
            return array('success' => true, 'data' => $response, 'code' => $httpCode);
        }
        
        // 最後一次嘗試失敗
        if ($attempt === $maxRetries) {
            return array(
                'success' => false,
                'error' => $httpCode ? "HTTP $httpCode" : (error_get_last()['message'] ?? 'Unknown error'),
                'code' => $httpCode,
                'attempts' => $attempt
            );
        }
        
        // 指數退避
        usleep($backoff * $attempt);
    }
}

// 使用
$result = httpGetWithRetry('https://api.example.com/data', 3, 5);
if ($result['success']) {
    $data = json_decode($result['data'], true);
} else {
    // 告警、降級、記錄
}

HTTPS 與代理支援

<?php
$opts = array(
    'http' => array(
        'method' => 'GET',
        'timeout' => 10,
        'header' => "User-Agent: MyApp/1.0\r\nAccept: application/json\r\n",
        'proxy' => 'tcp://proxy.example.com:8080', // 代理
        'request_fulluri' => true,                 // 代理需完整 URI
    ),
    'ssl' => array(
        'verify_peer' => true,
        'verify_peer_name' => true,
        'cafile' => '/etc/ssl/certs/ca-certificates.crt', // CA 憑證路徑
        'ciphers' => 'HIGH:!aNULL:!MD5:!3DES',
    )
);
$context = stream_context_create($opts);

替代方案:cURL(功能更強)

<?php
function curlGet($url, $timeout = 10) {
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT => 'MyApp/1.0',
    ));
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    return array(
        'success' => $response !== false && $httpCode >= 200 && $httpCode < 300,
        'data' => $response,
        'code' => $httpCode,
        'error' => $error
    );
}

選擇建議

場景推薦方案
簡單 GET、無依賴要求file_get_contents + stream_context
需 POST、Header、Cookie、代理、憑證cURL
高併發、非阻塞、協程Swoole / amphp / ReactPHP
現代框架專案Guzzle HTTP Client (PSR-7/18)

核心原則:永遠設定超時,檢查回傳值,記錄失敗日誌,實施重試與熔斷。

copyright © 萬盛學電腦網 all rights reserved