file_get_contents() 搭配 stream_context_create() 可發送 POST 請求,無需依賴 cURL 擴展。本文提供標準化封裝函數,支援 JSON、表單、自定義 Header、超時、重定向控制、SSL 驗證等完整選項。
<?php
$url = 'https://api.example.com/endpoint';
$data = [
'name' => 'Joe',
'website' => 'www.example.com'
];
// 1. 表單格式
$postData = http_build_query($data);
// 2. 建立 Stream Context
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($postData) . "\r\n",
'content' => $postData,
'timeout' => 30, // 秒
'follow_location' => 1, // 跟隨重定向
'max_redirects' => 3,
'ignore_errors' => true, // 即使 4xx/5xx 也返回內容
],
'ssl' => [
'verify_peer' => false, // 開發環境可關閉,生產必須開啟
'verify_peer_name' => false,
]
]);
// 3. 發送請求
$response = file_get_contents($url, false, $context);
$httpCode = 0;
if (isset($http_response_header)) {
foreach ($http_response_header as $header) {
if (stripos($header, 'HTTP/') === 0) {
$httpCode = (int)explode(' ', $header)[1];
break;
}
}
}
echo "HTTP $httpCode\n";
echo $response;
?>
function postJson(string $url, array $data, int $timeout = 30): array {
$json = json_encode($data, JSON_UNESCAPED_UNICODE);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n" .
"Content-Length: " . strlen($json) . "\r\n" .
"Accept: application/json\r\n",
'content' => $json,
'timeout' => $timeout,
'ignore_errors' => true,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
]
]);
$response = file_get_contents($url, false, $context);
$code = 0;
if (isset($http_response_header[0])) {
$code = (int)explode(' ', $http_response_header[0])[1];
}
return [
'code' => $code,
'body' => $response,
'json' => $response ? json_decode($response, true) : null,
];
}
// 使用
$result = postJson('https://httpbin.org/post', ['foo' => 'bar']);
var_dump($result);
function postFile(string $url, string $filePath, string $fieldName = 'file', array $extraFields = []): array {
$boundary = uniqid('boundary_');
$body = '';
// 額外欄位
foreach ($extraFields as $name => $value) {
$body .= "--$boundary\r\n";
$body .= "Content-Disposition: form-data; name=\"$name\"\r\n\r\n";
$body .= "$value\r\n";
}
// 檔案
$fileName = basename($filePath);
$mime = mime_content_type($filePath) ?: 'application/octet-stream';
$content = file_get_contents($filePath);
$body .= "--$boundary\r\n";
$body .= "Content-Disposition: form-data; name=\"$fieldName\"; filename=\"$fileName\"\r\n";
$body .= "Content-Type: $mime\r\n\r\n";
$body .= $content . "\r\n";
$body .= "--$boundary--\r\n";
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: multipart/form-data; boundary=$boundary\r\n" .
"Content-Length: " . strlen($body) . "\r\n",
'content' => $body,
'timeout' => 60,
]
]);
$response = file_get_contents($url, false, $context);
return ['body' => $response];
}
| 選項 | 預設值 | 說明 |
|---|---|---|
| method | GET | HTTP 方法:GET/POST/PUT/DELETE 等 |
| header | - | 請求 Header 字串,多行用 \r\n 分隔 |
| content | - | 請求 Body 字串 |
| timeout | default_socket_timeout (60s) | 讀寫超時秒數 |
| follow_location | 1 | 是否跟隨 3xx 重定向 |
| max_redirects | 20 | 最大重定向次數 |
| ignore_errors | 0 | 1=即使 4xx/5xx 也返回 Body,不拋警告 |
| protocol_version | 1.0 | 1.0 或 1.1(Keep-Alive 需 1.1) |
| user_agent | PHP/版本 | 自定義 User-Agent |
try {
$result = postJson($url, $data);
if ($result['code'] >= 400) {
throw new Exception("HTTP {$result['code']}: " . substr($result['body'], 0, 200));
}
// 成功處理 $result['json']
} catch (Exception $e) {
error_log("API Request Failed: " . $e->getMessage());
// 降級/重試/告警
}
| 特性 | file_get_contents + stream | cURL |
|---|---|---|
| 依賴 | PHP 核心(無額外擴展) | 需 php-curl 擴展 |
| 多工/並發 | 不支援(阻塞) | 支援 curl_multi |
| 協議支援 | HTTP/HTTPS/FTP/檔案 | 更豐富(SFTP、LDAP、MQTT 等) |
| 效能 | 單請求略低 | 高併發優勢明顯 |
| 代理/認證 | 基礎支援 | 完整支援(NTLM、Kerberos、SOCKS5) |
簡單場景用 file_get_contents,複雜/高併發場景請用 cURL 或 Guzzle(現代 PHP HTTP 客戶端標準)。