萬盛學電腦網

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

PHP 讀取遠端檔案/網頁內容六大方法完整比較

方法比較總覽

方法支援協定POST 支援Header 存取效能靈活度
file_get_contentsHTTP/HTTPS/FTP/檔案需 Stream Context需 $http_response_header中中
fopen/freadHTTP/HTTPS/FTP/檔案需 Stream Contextstream_get_meta_data()中中
fsockopenTCP/SSL (原始 Socket)手動組裝完整控制高(底層)高(複雜)
cURL所有主流協定原生支援完整控制最高最高
GuzzleHTTP/HTTPS物件導向完整控制高最高(現代)
HTTP_Request2HTTP/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)
copyright © 萬盛學電腦網 all rights reserved