stream_context_create() + file_get_contents()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;
}
<?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);
}
<?php
$response = http_request(
'https://api.example.com/login',
['username' => 'admin', 'password' => 'secret'],
'',
'POST',
10
);
if ($response !== false) {
echo $response;
}
<?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]]]);
<?php
// 僅開發/測試環境使用!生產環境請配置正確 CA 憑證
$opts['http']['ssl'] = [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
];
| 場景 | 建議 |
|---|---|
| 簡單 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)。