方法比較總覽
| 方法 | 支援協定 | POST 支援 | Header 存取 | 效能 | 靈活度 |
file_get_contents | HTTP/HTTPS/FTP/檔案 | 需 Stream Context | 需 $http_response_header | 中 | 中 |
fopen/fread | HTTP/HTTPS/FTP/檔案 | 需 Stream Context | stream_get_meta_data() | 中 | 中 |
fsockopen | TCP/SSL (原始 Socket) | 手動組裝 | 完整控制 | 高(底層) | 高(複雜) |
cURL | 所有主流協定 | 原生支援 | 完整控制 | 最高 | 最高 |
Guzzle | HTTP/HTTPS | 物件導向 | 完整控制 | 高 | 最高(現代) |
HTTP_Request2 | HTTP/HTTPS | 物件導向 | 完整控制 | 中 | 高 |
1. file_get_contents (GET)
$url = 'https://www.baidu.com/';
$html = file_get_contents($url);
// 回應標頭自動存入 $http_response_header 陣列
print_r($http_response_header);
2. fopen + fread (GET)
$fp = fopen($url, 'r');
$meta = stream_get_meta_data($fp); // 取得 header 等中繼資料
while (!feof($fp)) {
$result .= fgets($fp, 1024);
}
fclose($fp);
3. file_get_contents (POST) - Stream Context
'bar'];
$postData = http_build_query($data);
$opts = [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($postData) . "\r\n",
'content' => $postData,
'timeout' => 30,
],
'ssl' => [
'verify_peer' => false, // 僅測試用
'verify_peer_name' => false,
]
];
$context = stream_context_create($opts);
$html = file_get_contents('https://localhost/api', false, $context);
4. fsockopen (GET) - 原始 Socket
function getUrl($url, $cookie = '') {
$parts = parse_url($url);
$query = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
$host = $parts['host'];
$port = $parts['port'] ?? 80;
$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) return false;
$req = "GET $query HTTP/1.1\r\n";
$req .= "Host: $host\r\n";
$req .= "Connection: Close\r\n";
if ($cookie) $req .= "Cookie: $cookie\r\n";
$req .= "\r\n";
fwrite($fp, $req);
$response = '';
while (!feof($fp)) $response .= fgets($fp, 1024);
fclose($fp);
return $response; // 含 Header + Body
}
function getUrlHtml($url, $cookie = '') {
$raw = getUrl($url, $cookie);
if (!$raw) return false;
$bodyStart = strpos($raw, "\r\n\r\n");
return $bodyStart !== false ? substr($raw, $bodyStart + 4) : '';
}
5. fsockopen (POST) - 原始 Socket
function httpPost($url, $data, $cookie = '', $referer = '') {
$parts = parse_url($url);
$host = $parts['host'];
$port = $parts['port'] ?? 80;
$path = $parts['path'] . ($parts['query'] ? '?' . $parts['query'] : '');
$postData = http_build_query($data);
$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) return false;
$req = "POST $path HTTP/1.1\r\n";
$req .= "Host: $host\r\n";
$req .= "Referer: $referer\r\n";
$req .= "Content-Type: application/x-www-form-urlencoded\r\n";
$req .= "Content-Length: " . strlen($postData) . "\r\n";
$req .= "Connection: Close\r\n";
if ($cookie) $req .= "Cookie: $cookie\r\n";
$req .= "\r\n";
$req .= $postData;
fwrite($fp, $req);
$response = '';
while (!feof($fp)) $response .= fgets($fp, 1024);
fclose($fp);
return $response;
}
6. cURL (推薦生產環境)
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://www.baidu.com/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_USERAGENT => 'Mozilla/5.0 ...',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_SSL_VERIFYPEER => true, // 生產必開
CURLOPT_SSL_VERIFYHOST => 2,
]);
$html = curl_exec($ch);
if ($html === false) {
echo 'cURL Error: ' . curl_error($ch);
}
curl_close($ch);
cURL 進階:POST + JSON + Header 完整範例
$data = ['name' => 'John', 'age' => 30];
$ch = curl_init('https://api.example.com/users');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $token,
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
實用工具函數
function printArray(array $arr) {
echo "
Row count: " . count($arr) . "
";
foreach ($arr as $k => $v) echo "$k=$value
";
}
選擇建議
- 簡單 GET、允許
allow_url_fopen → file_get_contents
- 需控制 Header、Cookie、POST、重導向、逾時、憑證 → cURL
- 現代專案 → Guzzle (Composer:
guzzlehttp/guzzle):Promise、Middleware、PSR-7/18 相容
- 極簡環境無擴充 →
fsockopen (純 Socket)