首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 以 file_get_contents 替代 cURL 發送 GET/POST 請求

     編輯:PHP 綜合知識

適用場景

當伺服器環境未安裝或禁用 cURL 擴展、cURL 不支援 HTTPS 導致 502 錯誤、或不想重新編譯 PHP 環境時,file_get_contents 配合 Stream Context 是優雅的替代方案。

GET 請求:一行搞定

<?php
$url = 'https://api.example.com/users?page=1';
$response = file_get_contents($url);
// 直接取得回應內容(字串)
$data = json_decode($response, true);
?>

POST 請求:需建立 Stream Context

<?php
/**
 * 發送 POST 請求並取得回應
 *
 * @param string $url 目標網址
 * @param array  $postData 陣列形式的 POST 欄位
 * @return string|false 回應內容或失敗
 */
function postRequest($url, array $postData = []) {
    $options = [
        'http' => [
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => http_build_query($postData),
            'timeout' => 30, // 秒
        ],
        'ssl' => [
            'verify_peer'      => false, // 僅測試環境建議關閉驗證
            'verify_peer_name' => false,
        ],
    ];
    $context = stream_context_create($options);
    return file_get_contents($url, false, $context);
}

// === 使用範例 ===
$apiUrl = 'https://api.example.com/login';
$payload = [
    'username' => 'demo_user',
    'password' => 'secret123',
    'remember' => '1',
];

$result = postRequest($apiUrl, $payload);
if ($result !== false) {
    $json = json_decode($result, true);
    var_dump($json);
} else {
    error_log("POST 請求失敗: $apiUrl");
}
?>

關鍵參數詳細說明

選項說明常用值
methodHTTP 方法GET, POST, PUT, DELETE
header自訂請求標頭(多行用 \r\n 分隔)Content-type: application/json, Authorization: Bearer xxx
content請求主體內容http_build_query($arr) 或 json_encode($arr)
timeout連線/讀取逾時(秒)30
follow_location是否自動追蹤 3xx 重導向1 (預設)
max_redirects最大重導向次數5
ssl.verify_peer驗證 SSL 憑證生產環境 true,測試可 false

進階:發送 JSON 資料

<?php
function postJson($url, array $data) {
    $options = [
        'http' => [
            'method'  => 'POST',
            'header'  => 'Content-type: application/json',
            'content' => json_encode($data),
            'timeout' => 30,
        ],
    ];
    return file_get_contents($url, false, stream_context_create($options));
}

// 使用
$resp = postJson('https://api.example.com/orders', [
    'items' => [['id' => 1, 'qty' => 2], ['id' => 3, 'qty' => 1]],
    'shipping' => 'express',
]);
?>

效能與限制比較

  • 優點:零相依、內建函數、語法簡潔、支援 HTTPS(需 OpenSSL)。
  • 缺點:無法輕易取得 HTTP 狀態碼、回應標頭、錯誤處理較弱、不支援並發請求、大檔案上傳記憶體佔用高。
  • 建議:簡單 GET/POST、低併發場景用 file_get_contents;複雜互動、需精確控制標頭/狀態碼、高併發、檔案上傳仍首選 cURL 或 Guzzle/HttpClient 等成熟函式庫。

善用 Stream Context,讓 file_get_contents 成為輕量級 HTTP 客戶端的得力選項。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved