一、基本文件讀取
| 函數 | 特點 | 適用場景 |
file_get_contents() | 一次性讀入內存,支持 URL(需 allow_url_fopen),簡潔 | 小文件、簡單 GET 請求 |
fopen() + fread()/stream_get_contents() | 流式讀取,可控制指針、分塊讀取、獲取元數據 | 大文件、需處理響應頭、二進制文件 |
readfile() | 直接輸出到輸出緩衝,不佔用 PHP 內存 | 文件下載輸出、圖片代理 |
file() | 按行讀入數組 | 逐行處理文本、配置文件解析 |
二、獲取 HTTP 響應頭與元數據
<?php
// file_get_contents 自動填充 $http_response_header
$html = file_get_contents('https://api.example.com/data');
print_r($http_response_header);
/*
Array
(
[0] => HTTP/1.1 200 OK
[1] => Content-Type: application/json
[2] => Content-Length: 123
...
)
*/
// fopen 獲取流元數據
$fp = fopen('https://api.example.com/data', 'r');
$meta = stream_get_meta_data($fp);
print_r($meta['wrapper_data']); // 響應頭數組
fclose($fp);
?>
三、Stream Context:自定義請求(POST、Header、Cookie、超時)
<?php
$postData = http_build_query(['user' => 'admin', 'pass' => '123456']);
$options = [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($postData) . "\r\n" .
"User-Agent: MyApp/1.0\r\n",
'content' => $postData,
'timeout' => 10, // 秒
'ignore_errors' => true, // 獲取 4xx/5xx 响应体
],
'ssl' => [
'verify_peer' => false, // 僅測試環境
'verify_peer_name' => false,
]
];
$context = stream_context_create($options);
$response = file_get_contents('https://api.example.com/login', false, $context);
// 解析響應碼
preg_match('/HTTP\/\d\.\d\s+(\d+)/', $http_response_header[0], $matches);
$statusCode = (int)$matches[1];
?>
四、cURL:功能最強大的 HTTP 客戶端
<?php
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.example.com/data',
CURLOPT_RETURNTRANSFER => true, // 返回字符串而非直接輸出
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => ['key' => 'value'],
CURLOPT_HTTPHEADER => [
'Authorization: Bearer token123',
'Accept: application/json',
],
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => false, // 僅測試
CURLOPT_FOLLOWLOCATION => true, // 跟隨重定向
CURLOPT_MAXREDIRS => 5,
CURLOPT_COOKIEJAR => '/tmp/cookies.txt', // 持久化 Cookie
CURLOPT_COOKIEFILE => '/tmp/cookies.txt',
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch); // 詳細傳輸信息
curl_close($ch);
if ($errno) {
throw new Exception("cURL Error ($errno): $error");
}
?>
五、cURL 多請求並發(curl_multi)
<?php
$urls = [
'https://api1.example.com',
'https://api2.example.com',
'https://api3.example.com',
];
$handles = [];
$mh = curl_multi_init();
foreach ($urls as $url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh, $ch);
$handles[$url] = $ch;
}
$running = null;
do {
curl_multi_exec($mh, $running);
curl_multi_select($mh); // 等待活動
} while ($running);
$results = [];
foreach ($handles as $url => $ch) {
$results[$url] = curl_multi_getcontent($ch);
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
?>
六、選擇建議
- 簡單 GET、小文件:
file_get_contents
- 需自定義 Header、POST、Cookie、超時:Stream Context 或 cURL
- 高併發、複雜交互、需調試信息:cURL
- 大文件下載/代理:
fopen 流式 + readfile 輸出
- 現代專案:推薦使用 GuzzleHttp/Guzzle (PSR-18 客戶端),封裝更優雅、支持異步、中間件。