萬盛學電腦網

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

PHP file_get_contents 完整指南:讀取本地/遠端檔案、串流上下文、錯誤處理與大檔案記憶體優化

函式原型

file_get_contents(
    string $filename,
    bool $use_include_path = false,
    ?resource $context = null,
    int $offset = 0,
    int $length = -1
): string|false

基本用法

<?php
// 1. 讀取本地檔案
$content = file_get_contents('/path/to/file.txt');
if ($content === false) {
    throw new RuntimeException("讀取失敗");
}

// 2. 讀取遠端 URL (需 php.ini allow_url_fopen=On)
$html = file_get_contents('https://api.example.com/data.json');
$data = json_decode($html, true);

// 3. 部分讀取 (offset/length)
$header = file_get_contents('large.log', false, null, 0, 1024); // 前 1KB

串流上下文 : 進階控制

$context = stream_context_create([
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-Type: application/json\r\nAuthorization: Bearer $token",
        'content' => json_encode(['key' => 'value']),
        'timeout' => 10,
        'follow_location' => 1,
        'max_redirects' => 3,
        'ignore_errors' => true, // 取得 4xx/5xx 回應內容
    ],
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true,
        // 'cafile' => '/path/to/ca-bundle.crt',
    ],
]);

$response = file_get_contents('https://api.example.com/endpoint', false, $context);
$httpCode = $http_response_header[0] ?? ''; // 取得 HTTP 狀態碼

實務封裝:健壯的 HTTP 客戶端

class HttpClient {
    public function get(string $url, array $options = []): string {
        return $this->request('GET', $url, $options);
    }
    
    public function post(string $url, array $data, array $options = []): string {
        $options['http']['method'] = 'POST';
        $options['http']['content'] = json_encode($data);
        $options['http']['header'] = ($options['http']['header'] ?? '') 
            . "\r\nContent-Type: application/json";
        return $this->request('POST', $url, $options);
    }
    
    private function request(string $method, string $url, array $options): string {
        $defaultOptions = [
            'http' => [
                'timeout' => 10,
                'follow_location' => 1,
                'max_redirects' => 5,
                'ignore_errors' => true,
            ],
            'ssl' => [
                'verify_peer' => true,
            ],
        ];
        
        $context = stream_context_create(array_replace_recursive($defaultOptions, $options));
        $content = @file_get_contents($url, false, $context);
        
        if ($content === false) {
            $error = error_get_last();
            throw new RuntimeException("HTTP $method $url 失敗: " . ($error['message'] ?? '未知錯誤'));
        }
        
        // 檢查 HTTP 狀態碼
        $statusLine = $http_response_header[0] ?? '';
        if (preg_match('/HTTP\/\d\.\d\s+(\d{3})/', $statusLine, $m)) {
            $code = (int)$m[1];
            if ($code >= 400) {
                throw new HttpException("HTTP $code", $code, $content);
            }
        }
        
        return $content;
    }
}

大檔案處理:避免記憶體耗盡

file_get_contents 會將整個檔案載入記憶體。大檔案請用串流:

// 逐行處理
$handle = fopen('huge.log', 'r');
while (($line = fgets($handle)) !== false) {
    processLine($line);
}
fclose($handle);

// 或用 SplFileObject
$file = new SplFileObject('huge.csv');
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    processRow($row);
}

// 複製大檔案 (不進記憶體)
copy('source.iso', 'dest.iso'); // 內核層面 copy
// 或
stream_copy_to_stream(fopen('src', 'r'), fopen('dest', 'w'));

常見問題與解決

問題原因解決
允許 URL fopen 失效php.ini allow_url_fopen=Off改用 cURL 或開啟設定
HTTPS 憑證驗證失敗缺少 CA 憑證設定 ssl.cafile 或更新 ca-certificates
中文檔名亂碼檔案系統編碼不一致用 rawurlencode、iconv、或避免中文檔名
超時預設 60 秒 (php.ini default_socket_timeout)stream_context 設定 timeout
回應截斷伺服器無 Content-Length、Chunked 編碼問題ignore_errors=true、檢查 Transfer-Encoding

效能比較

  • file_get_contents vs cURL:簡單 GET 請求前者較簡潔,cURL 功能更完整 (Cookie、認證、並發、進度回調)
  • 本地檔案:file_get_contents 經優化,中小檔案最快
  • 大檔案:串流 (fopen/fread) 或 copy()、stream_copy_to_stream()
copyright © 萬盛學電腦網 all rights reserved