HttpRequest (PECL pecl_http) 提供物件導向、流暢介面的 HTTP 客戶端,支援並發請求、Cookie 管理、檔案上傳、回調處理。注意:PHP 7+ 核心已移除,需安裝 pecl install pecl_http,現代專案建議改用 Guzzle 或 Symfony HttpClient。本文為維護舊專案或學習參考。
# Ubuntu/Debian
apt-get install php-http php-raphf php-propro
pecl install pecl_http
echo "extension=http.so" > /etc/php/8.x/mods-available/http.ini
phpenmod http
| 方法 | 說明 |
|---|---|
__construct(string $url, int $method = METH_GET) | 建立請求物件 |
setOptions(array $options) | 設定 cURL 選項陣列 |
addQueryData(array $params) | 添加 GET 參數 |
addPostFields(array $fields) | 添加 POST 表單欄位 |
addPostFile(string $name, string $path, string $type) | 添加檔案上傳 (multipart/form-data) |
send() | 發送請求,返回 HttpMessage 回應物件 |
getResponseCode() | 取得 HTTP 狀態碼 |
getResponseBody() | 取得回應主體字串 |
getResponseHeader(string $name) | 取得特定回應標頭 |
<?php
$r = new HttpRequest('https://example.com/feed.rss', HttpRequest::METH_GET);
// 條件請求:若本地快取未修改則返回 304
$r->setOptions(['lastmodified' => filemtime('local.rss') ?? 0]);
$r->addQueryData(['category' => 3]);
try {
$r->send();
if ($r->getResponseCode() === 200) {
file_put_contents('local.rss', $r->getResponseBody());
echo "RSS 更新並儲存成功\n";
} elseif ($r->getResponseCode() === 304) {
echo "RSS 未變更,使用本地快取\n";
} else {
echo "請求失敗: " . $r->getResponseCode() . "\n";
}
} catch (HttpException $ex) {
echo "網路錯誤: $ex\n";
}
<?php
$r = new HttpRequest('https://api.example.com/upload', HttpRequest::METH_POST);
$r->setOptions([
'cookies' => ['session_id' => 'abc123', 'lang' => 'zh-TW'],
'timeout' => 30,
]);
$r->addPostFields([
'user' => 'mike',
'action' => 'upload_avatar',
]);
$r->addPostFile('avatar', '/path/to/photo.jpg', 'image/jpeg');
try {
$responseBody = $r->send()->getBody();
echo $responseBody;
} catch (HttpException $ex) {
echo "上傳失敗: $ex\n";
}
composer require guzzlehttp/guzzle
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client([
'base_uri' => 'https://api.example.com/',
'timeout' => 30,
'cookies' => true, // 自動管理 Cookie Jar
]);
// GET
$resp = $client->get('feed.rss', ['query' => ['category' => 3]]);
if ($resp->getStatusCode() === 200) {
file_put_contents('local.rss', $resp->getBody());
}
// POST with multipart
$resp = $client->post('upload', [
'multipart' => [
['name' => 'user', 'contents' => 'mike'],
['name' => 'avatar', 'contents' => fopen('/path/to/photo.jpg', 'r'), 'filename' => 'photo.jpg'],
],
]);
echo $resp->getBody();
robots.txt (User-agent: * / Disallow: /)。User-Agent 標識機器人身份,並提供聯絡方式。sleep()、Token Bucket),避免對目標服務器造成壓力。Terms of Service、著作權法、個資法 (GDPR/PDPA)。