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 狀態碼
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 經優化,中小檔案最快copy()、stream_copy_to_stream()