萬盛學電腦網

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

PHP 獲取 HTTP 內容通用函數:支援 GET/POST、Cookie、超時、User-Agent

函數設計目標

  • 統一封裝 stream_context_create() + file_get_contents()
  • 支援 GET/POST、自定義 Header、Cookie、User-Agent、超時
  • 自動帶入當前請求的 User-Agent,模擬瀏覽器行為
  • 返回原始回應內容(含 HTML/JSON/二進位),錯誤返回 false

完整函數代碼

<?php
/**
 * 通用 HTTP 請求函數
 *
 * @param string $url       目標 URL
 * @param string|array $data  GET: 查詢字串或陣列;POST: 表單資料陣列
 * @param string $cookie    Cookie 字串(可選)
 * @param string $method    'GET' 或 'POST'
 * @param int    $timeout   逾時秒數,預設 60
 * @return string|false     回應內容,失敗返回 false
 */
function http_request(string $url, $data = '', string $cookie = '', string $method = 'GET', int $timeout = 60) {
    $opts = [
        'http' => [
            'method'      => strtoupper($method),
            'user_agent'  => $_SERVER['HTTP_USER_AGENT'] ?? 'PHP/' . PHP_VERSION,
            'timeout'     => $timeout,
            'ignore_errors' => true, // 取得 4xx/5xx 回應內容而非拋出 warning
        ]
    ];

    if (strtoupper($method) === 'POST') {
        $postData = is_array($data) ? http_build_query($data) : $data;
        $opts['http']['header'] = implode("\r\n", [
            'Content-Type: application/x-www-form-urlencoded',
            'Content-Length: ' . strlen($postData),
            'Connection: close',
        ]);
        if ($cookie) $opts['http']['header'] .= "\r\nCookie: $cookie";
        $opts['http']['content'] = $postData;
    } else {
        // GET: 將 data 附加到 URL
        if (is_array($data)) $data = http_build_query($data);
        if ($data) {
            $url .= (strpos($url, '?') === false ? '?' : '&') . $data;
        }
        if ($cookie) {
            $opts['http']['header'] = "Cookie: $cookie\r\nConnection: close";
        }
    }

    $context = stream_context_create($opts);
    $result = @file_get_contents($url, false, $context);

    // 可選:檢查 HTTP 狀態碼(需 PHP 7.1+ $http_response_header)
    // if (isset($http_response_header[0]) && !preg_match('/^HTTP\/\d\.\d\s+2\d\d/', $http_response_header[0])) {
    //     return false;
    // }

    return $result;
}

使用範例

GET 請求攜帶參數與 Cookie

<?php
$html = http_request('https://api.example.com/user', ['id' => 123], 'session=abc123; theme=dark');
if ($html !== false) {
    $user = json_decode($html, true);
    print_r($user);
}

POST 表單提交

<?php
$response = http_request(
    'https://api.example.com/login',
    ['username' => 'admin', 'password' => 'secret'],
    '',
    'POST',
    10
);
if ($response !== false) {
    echo $response;
}

POST JSON 資料(API 常用)

<?php
function http_post_json(string $url, array $payload, int $timeout = 10): ?array {
    $opts = [
        'http' => [
            'method'  => 'POST',
            'header'  => "Content-Type: application/json\r\nConnection: close",
            'content' => json_encode($payload, JSON_UNESCAPED_UNICODE),
            'timeout' => $timeout,
            'ignore_errors' => true,
        ]
    ];
    $ctx = stream_context_create($opts);
    $resp = @file_get_contents($url, false, $ctx);
    return $resp ? json_decode($resp, true) : null;
}

// 使用
$result = http_post_json('https://api.example.com/orders', ['items' => [[1,2],[3,4]]]);

進階:處理 HTTPS/SSL 憑證問題

<?php
// 僅開發/測試環境使用!生產環境請配置正確 CA 憑證
$opts['http']['ssl'] = [
    'verify_peer'      => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true,
];

為什麼不用 cURL?

場景建議
簡單 GET/POST、無複雜重導向/認證file_get_contents + Stream Context 輕量、零依賴
需支援 HTTP/2、多路複用、並發、進度回調cURL (或 ext-http/Guzzle/Http\Client)
需處理複雜 Cookie Jar、自動重導向限制、代理認證cURL/Guzzle
舊版 PHP 無 cURL 擴展Stream 是唯一選擇

錯誤處理最佳實踐

<?php
function safe_http_request(string $url, array $options = []): array {
    $defaultOpts = [
        'method'  => 'GET',
        'data'    => null,
        'cookie'  => '',
        'timeout' => 10,
    ];
    $opts = array_merge($defaultOpts, $options);

    $context = stream_context_create(['http' => [
        'method'       => $opts['method'],
        'user_agent'   => 'MyApp/1.0',
        'timeout'      => $opts['timeout'],
        'ignore_errors'=> true,
        'header'       => $opts['cookie'] ? "Cookie: {$opts['cookie']}\r\nConnection: close" : 'Connection: close',
        'content'      => $opts['method'] === 'POST' && $opts['data']
                           ? (is_array($opts['data']) ? http_build_query($opts['data']) : $opts['data'])
                           : null,
    ]]);

    $content = @file_get_contents($url, false, $context);
    $status = 0;
    if (isset($http_response_header[0])) {
        preg_match('/HTTP\/\d\.\d\s+(\d{3})/', $http_response_header[0], $m);
        $status = (int)($m[1] ?? 0);
    }

    return [
        'status'  => $status,
        'body'    => $content,
        'headers' => $http_response_header ?? [],
        'ok'      => $content !== false && $status >= 200 && $status < 300,
    ];
}

提示:生產環境建議封裝為 Service 類,注入 HttpClient 介面(如 Psr\Http\Client\ClientInterface),便於測試與替換底層實現(Guzzle/Swoole/cURL)。

copyright © 萬盛學電腦網 all rights reserved