當伺服器環境未安裝或禁用 cURL 擴展、cURL 不支援 HTTPS 導致 502 錯誤、或不想重新編譯 PHP 環境時,file_get_contents 配合 Stream Context 是優雅的替代方案。
<?php
$url = 'https://api.example.com/users?page=1';
$response = file_get_contents($url);
// 直接取得回應內容(字串)
$data = json_decode($response, true);
?>
<?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");
}
?>
| 選項 | 說明 | 常用值 |
|---|---|---|
method | HTTP 方法 | 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 |
<?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',
]);
?>
file_get_contents;複雜互動、需精確控制標頭/狀態碼、高併發、檔案上傳仍首選 cURL 或 Guzzle/HttpClient 等成熟函式庫。善用 Stream Context,讓 file_get_contents 成為輕量級 HTTP 客戶端的得力選項。