萬盛學電腦網

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

PHP 取得遠端網路檔案內容的完整方法 (fopen、cURL、file_get_contents、Guzzle)

四大核心方法對比

方法需求功能豐富度效能錯誤處理推薦場景
file_get_contents()allow_url_fopen=On基礎中簡單 (false/@)簡單 GET、小檔案、快速原型
fopen() + fread()allow_url_fopen=On串流控制中手動大檔案串流、自訂標頭、需逐塊處理
cURLphp-curl 擴充完整 (HTTP/2、代理、憑證、Cookie、多工)高完整 (curl_errno/error)**生產環境標準**、複雜請求
Guzzle (套件)Composer 安裝極豐富 (中介軟體、異步、重試、PSR-7/18)高例外體系、中介軟體**現代專案首選**、API 客戶端

方法一:file_get_contents (最簡單)

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

// 基本用法
$content = @file_get_contents($url);
if ($content === false) {
    die("無法取得遠端內容");
}

// 進階:自訂標頭、方法、超時 (需 stream context)
$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => "User-Agent: MyApp/1.0\r\nAccept: application/json\r\n",
        'timeout' => 10, // 秒
        'ignore_errors' => true, // 取得 4xx/5xx 內容而非報錯
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
    ],
]);

$content = file_get_contents($url, false, $context);
$httpCode = $http_response_header[0] ?? ''; // 取得狀態碼
// HTTP/1.1 200 OK

方法二:fopen 串流讀取 (大檔案/記憶體控制)

<?php
$url = 'https://speed.hetzner.de/100MB.bin';
$handle = fopen($url, 'rb'); // 二進位模式

if (!$handle) {
    die("連線失敗");
}

$totalSize = 0;
$chunkSize = 8192;
$outputFile = fopen('downloaded.bin', 'wb');

try {
    while (!feof($handle)) {
        $chunk = fread($handle, $chunkSize);
        if ($chunk === '') break;
        fwrite($outputFile, $chunk);
        $totalSize += strlen($chunk);
        
        // 進度顯示
        if ($totalSize % (1024*1024) === 0) {
            echo "已下載: " . ($totalSize / 1024 / 1024) . " MB\n";
        }
    }
} finally {
    fclose($handle);
    fclose($outputFile);
}
echo "下載完成,總大小: " . ($totalSize / 1024 / 1024) . " MB\n";

方法三:cURL 完整實戰範本 (生產環境標準)

<?php
function httpRequest(string $url, array $options = []): array
{
    $defaults = [
        'method' => 'GET',
        'headers' => [
            'User-Agent' => 'Mozilla/5.0 (compatible; PHP Bot)',
            'Accept' => 'application/json, text/html',
        ],
        'timeout' => 30,
        'connect_timeout' => 10,
        'follow_location' => true,
        'max_redirects' => 5,
        'proxy' => null,
        'proxy_auth' => null,
        'ssl_verify' => true,
        'post_fields' => null,
        'json' => null,
    ];
    $opts = array_merge($defaults, $options);
    
    $ch = curl_init();
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $opts['method'],
        CURLOPT_HTTPHEADER => array_map(fn($k, $v) => "$k: $v", array_keys($opts['headers']), $opts['headers']),
        CURLOPT_TIMEOUT => $opts['timeout'],
        CURLOPT_CONNECTTIMEOUT => $opts['connect_timeout'],
        CURLOPT_FOLLOWLOCATION => $opts['follow_location'],
        CURLOPT_MAXREDIRS => $opts['max_redirects'],
        CURLOPT_SSL_VERIFYPEER => $opts['ssl_verify'],
        CURLOPT_SSL_VERIFYHOST => $opts['ssl_verify'] ? 2 : 0,
        CURLOPT_ENCODING => 'gzip, deflate', // 自動解壓
    ]);
    
    if ($opts['proxy']) {
        curl_setopt($ch, CURLOPT_PROXY, $opts['proxy']);
        if ($opts['proxy_auth']) {
            curl_setopt($ch, CURLOPT_PROXYUSERPWD, $opts['proxy_auth']);
        }
    }
    
    if ($opts['json'] !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($opts['json']));
        $opts['headers']['Content-Type'] = 'application/json';
    } elseif ($opts['post_fields'] !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $opts['post_fields']);
    }
    
    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $error = curl_error($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    if ($errno) {
        throw new RuntimeException("cURL 錯誤 ($errno): $error");
    }
    
    return [
        'status' => $info['http_code'],
        'headers' => $info['request_header'] ?? [],
        'body' => $response,
        'info' => $info,
    ];
}

// 使用範例
try {
    // GET
    $result = httpRequest('https://httpbin.org/get');
    echo "狀態: {$result['status']}\n";
    
    // POST JSON
    $result = httpRequest('https://httpbin.org/post', [
        'method' => 'POST',
        'json' => ['name' => 'Tom', 'age' => 25],
    ]);
    echo $result['body'];
    
    // 下載大檔案 (串流寫入檔案)
    $fp = fopen('large.zip', 'wb');
    $ch = curl_init('https://example.com/large.zip');
    curl_setopt_array($ch, [
        CURLOPT_FILE => $fp,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => 300,
        CURLOPT_NOPROGRESS => false,
        CURLOPT_PROGRESSFUNCTION => function($resource, $dltotal, $dlnow) {
            if ($dltotal > 0) printf("\r進度: %.2f%%", $dlnow/$dltotal*100);
        },
    ]);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    
} catch (Exception $e) {
    echo "請求失敗: " . $e->getMessage();
}

方法四:Guzzle HTTP Client (現代 PHP 專案首選)

<?php
// composer require guzzlehttp/guzzle
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Response;

$client = new Client([
    'base_uri' => 'https://api.example.com/',
    'timeout' => 10.0,
    'headers' => [
        'User-Agent' => 'MyApp/1.0',
        'Accept' => 'application/json',
    ],
    // 中介軟體:自動重試、日誌、快取等
    'handler' => \GuzzleHttp\HandlerStack::create(),
]);

// 同步請求
try {
    $response = $client->get('users/1', [
        'query' => ['include' => 'posts'],
    ]);
    $user = json_decode($response->getBody()->getContents(), true);
    echo "用戶: {$user['name']}\n";
} catch (RequestException $e) {
    echo "請求失敗: " . $e->getMessage();
    if ($e->hasResponse()) {
        echo "狀態碼: " . $e->getResponse()->getStatusCode();
    }
}

// 非同步並發請求 (效能提升數倍)
$promises = [
    'users' => $client->getAsync('users'),
    'posts' => $client->getAsync('posts'),
    'comments' => $client->getAsync('comments'),
];

$results = \GuzzleHttp\Promise\Utils::unwrap($promises);
foreach ($results as $name => $response) {
    echo "$name: " . $response->getStatusCode() . "\n";
}

// 串流下載大檔案 (不佔記憶體)
$client->get('large-file.zip', [
    'sink' => fopen('large-file.zip', 'w'), // 直接寫入檔案
    'progress' => function($downloadTotal, $downloaded) {
        if ($downloadTotal > 0) printf("\r%.2f%%", $downloaded/$downloadTotal*100);
    },
]);

常見問題排查

問題原因解決
file_get_contents 失敗php.ini allow_url_fopen=Off改用 cURL 或開啟設定 (不建議)
SSL 憑證驗證失敗CA 憑證缺失/過期/自簽更新 ca-certificates、正確設定 CURLOPT_CAINFO、或暫時關閉驗證 (僅測試)
中文亂碼遠端編碼非 UTF-8iconv/mb_convert_encoding($content, 'UTF-8', 'GBK')
超時網路慢/對方無回應調整 timeout、connect_timeout、啟用 keep-alive
重導向循環伺服器設定錯誤限制 max_redirects、檢查 Location 標頭
大檔案記憶體爆炸一次性讀取串流下載 (fopen/curl CURLOPT_FILE/Guzzle sink)

最佳實踐總結

  1. 簡單腳本/單次請求:file_get_contents + stream context
  2. 生產環境 API 整合:Guzzle (PSR-18 相容、中介軟體生態、型別安全、測試友善)
  3. 需精細控制/舊專案/無 Composer:cURL 封裝工具類
  4. 大檔案下載/上傳:串流處理 (sink / CURLOPT_FILE / fopen fread)
  5. 統一錯誤處理:自訂例外類別、記錄請求/回應、監控告警
  6. 安全:驗證 SSL、限制重導向、過濾敏感標頭、設定超時
copyright © 萬盛學電腦網 all rights reserved