適用於無 cURL 擴展環境,或需精確控制 HTTP 協議細節(如自定義 Header 順序、Chunked 編碼)。
function httpPostSocket(string $host, string $path, array $data, int $port = 80, array $headers = []): ?string {
// 組裝 POST Body
$body = http_build_query($data);
$contentLength = strlen($body);
// 組裝 Request Header
$request = "POST $path HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
$request .= "Content-Type: application/x-www-form-urlencoded\r\n";
$request .= "Content-Length: $contentLength\r\n";
$request .= "Connection: Close\r\n";
foreach ($headers as $k => $v) {
$request .= "$k: $v\r\n";
}
$request .= "\r\n$body";
// 發送
$fp = @fsockopen($host, $port, $errno, $errstr, 10);
if (!$fp) return "連線失敗: $errstr ($errno)";
fwrite($fp, $request);
$response = '';
while (!feof($fp)) {
$response .= fgets($fp, 4096);
}
fclose($fp);
// 簡易分離 Header/Body
list($header, $body) = explode("\r\n\r\n", $response, 2) + ['', ''];
return $body;
}
// 使用範例:論壇登入
$resp = httpPostSocket('forum.example.com', '/bb-login.php', [
'user_login' => 'user',
'password' => 'pass',
'remember' => '1',
], 80, [
'User-Agent' => 'Mozilla/5.0',
'Referer' => 'https://forum.example.com/bb-login.php',
]);
var_dump($resp);
function httpPostCurl(string $url, array $data, array $options = []): ?string {
$ch = curl_init($url);
$defaultOptions = [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_COOKIEJAR => sys_get_temp_dir() . '/cookie.txt', // 持久化 Cookie
CURLOPT_COOKIEFILE => sys_get_temp_dir() . '/cookie.txt',
];
curl_setopt_array($ch, array_merge($defaultOptions, $options));
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno) return "cURL 錯誤 $errno: $error";
return $response;
}
// 使用
$resp = httpPostCurl('https://api.example.com/login', [
'username' => 'user',
'password' => 'pass',
]);
var_dump($resp);
$cookieFile = sys_get_temp_dir() . '/session_' . md5($targetHost) . '.txt';
function loginAndKeepSession(string $loginUrl, array $credentials, string $cookieFile): bool {
$ch = curl_init($loginUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $credentials,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEJAR => $cookieFile, // 寫入 Cookie
CURLOPT_COOKIEFILE => $cookieFile, // 讀取 Cookie
CURLOPT_FOLLOWLOCATION => true,
]);
$resp = curl_exec($ch);
$success = (curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) && strpos($resp, '登入成功') !== false;
curl_close($ch);
return $success;
}
// 後續請求自動攜帶 Cookie
function authenticatedRequest(string $url, string $cookieFile): ?string {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIEFILE => $cookieFile,
CURLOPT_COOKIEJAR => $cookieFile,
]);
$resp = curl_exec($ch);
curl_close($ch);
return $resp;
}
| 維度 | fsockopen | cURL |
|---|---|---|
| 依賴 | 核心函數,無擴展需求 | 需 php-curl 擴展 |
| HTTPS 支援 | 需手動實作 SSL (stream_socket_client + crypto) | 原生支援,一鍵開啟 |
| Cookie 管理 | 手動解析 Set-Cookie / 發送 Cookie | 內建 CookieJar/CookieFile |
| 重導向處理 | 手動解析 Location 並再請求 | CURLOPT_FOLLOWLOCATION 自動 |
| 多工/並行 | 需自行實作 stream_select | curl_multi 原生支援 |
| 推薦場景 | 極簡環境、教學、特殊協議 | 生產環境、API 整合、爬蟲、模擬登入 |