萬盛學電腦網

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

PHP file_get_contents POST 請求實現:Stream Context 完整配置指南

file_get_contents() 搭配 stream_context_create() 可發送 POST 請求,無需依賴 cURL 擴展。本文提供標準化封裝函數,支援 JSON、表單、自定義 Header、超時、重定向控制、SSL 驗證等完整選項。

基礎 POST 範例

<?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;
?>

JSON API 專用封裝

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];
}

關鍵 Context 選項對照表

選項預設值說明
methodGETHTTP 方法:GET/POST/PUT/DELETE 等
header-請求 Header 字串,多行用 \r\n 分隔
content-請求 Body 字串
timeoutdefault_socket_timeout (60s)讀寫超時秒數
follow_location1是否跟隨 3xx 重定向
max_redirects20最大重定向次數
ignore_errors01=即使 4xx/5xx 也返回 Body,不拋警告
protocol_version1.01.0 或 1.1(Keep-Alive 需 1.1)
user_agentPHP/版本自定義 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 vs cURL

特性file_get_contents + streamcURL
依賴PHP 核心(無額外擴展)需 php-curl 擴展
多工/並發不支援(阻塞)支援 curl_multi
協議支援HTTP/HTTPS/FTP/檔案更豐富(SFTP、LDAP、MQTT 等)
效能單請求略低高併發優勢明顯
代理/認證基礎支援完整支援(NTLM、Kerberos、SOCKS5)

簡單場景用 file_get_contents,複雜/高併發場景請用 cURL 或 Guzzle(現代 PHP HTTP 客戶端標準)。

copyright © 萬盛學電腦網 all rights reserved