在沒有 cURL 擴展、或需深度控制底層協議細節(如自定 Header、處理特殊重導向)時,PHP 內建的 fsockopen 可直接建立 TCP 連線,手動發送原始 HTTP 封包,實現 GET/POST 模擬請求。
以下封裝兩個函數,分別處理 GET 與 POST 請求,支援自定 Query String、Header、Referer、Content-Length 等。
<?php
/**
* 模擬 HTTP GET 請求
* @param string $url 目標 URL(含 query string)
* @param string $query 額外查詢參數(可選)
*/
function sock_get($url, $query = '') {
$info = parse_url($url);
$host = $info['host'];
$port = isset($info['port']) ? $info['port'] : 80;
$path = $info['path'] ?? '/';
$queryString = $info['query'] ?? '';
if ($query) {
$queryString = $queryString ? $queryString . '&' . $query : $query;
}
$fp = fsockopen($host, $port, $errno, $errstr, 3);
if (!$fp) {
throw new Exception("連線失敗: $errstr ($errno)");
}
$request = "GET $path?$queryString HTTP/1.0\r\n";
$request .= "Host: $host\r\n";
$request .= "\r\n";
fwrite($fp, $request);
$response = '';
while (!feof($fp)) {
$response .= fread($fp, 4096);
}
fclose($fp);
return $response;
}
/**
* 模擬 HTTP POST 請求
* @param string $url 目標 URL
* @param string $query POST 資料(application/x-www-form-urlencoded 格式)
*/
function sock_post($url, $query = '') {
$info = parse_url($url);
$host = $info['host'];
$port = isset($info['port']) ? $info['port'] : 80;
$path = $info['path'] ?? '/';
$queryString = $info['query'] ?? '';
$fp = fsockopen($host, $port, $errno, $errstr, 3);
if (!$fp) {
throw new Exception("連線失敗: $errstr ($errno)");
}
$request = "POST $path?$queryString HTTP/1.0\r\n";
$request .= "Host: $host\r\n";
$request .= "Referer: https://$host$path\r\n";
$request .= "Content-Type: application/x-www-form-urlencoded\r\n";
$request .= "Content-Length: " . strlen($query) . "\r\n";
$request .= "\r\n";
$request .= $query;
fwrite($fp, $request);
$response = '';
while (!feof($fp)) {
$response .= fread($fp, 4096);
}
fclose($fp);
return $response;
}
// 使用範例
$targetUrl = "https://localhost/test.php?uu=rrrrrrrrrrrr";
echo sock_get($targetUrl, "uu=55555555555555555");
echo sock_post($targetUrl, "uu=rrrrrrrrrrrrrrrr");
?>
ssl:// 或 tls:// 前綴並連 port 443,但驗證憑證需額外處理。fsockopen 是理解 HTTP 協議運作的最佳教具,但在實務專案中,強烈建議使用 cURL 或 Guzzle 等成熟 HTTP Client,它們支援 HTTPS、自動重導向、Cookie 管理、多執行緒併發、超時控制等企業級功能,開發效率與穩定性遠超手工 Socket。