方法一:cURL 函式庫 (推薦)
<?php
$post_data = array(
'clientname' => 'test08',
'clientpasswd' => 'test08',
'submit' => 'submit'
);
$url = 'https://xxx.xxx.xxx.xx/xx/xxx/top.php';
// 組裝 POST 字串
$fields = '';
foreach ($post_data as $k => $v) {
$fields .= "$k=" . urlencode($v) . "&";
}
$fields = rtrim($fields, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // 支援 Cookie
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
方法二:fsockopen (Socket 原生實作)
<?php
$URL = 'https://xxx.xxx.xxx.xx/xx/xxx/top.php';
$post_data = array(
'clientname' => 'test08',
'clientpasswd' => 'test08',
'submit' => 'ログイン'
);
$referrer = '';
// 解析 URL
$URL_Info = parse_url($URL);
if ($referrer == "") $referrer = $_SERVER['SCRIPT_URI'];
// 組裝 POST 資料
$values = array();
foreach ($post_data as $key => $value) {
$values[] = "$key=" . urlencode($value);
}
$data_string = implode("&", $values);
// 預設連接埠 80
if (!isset($URL_Info["port"])) $URL_Info["port"] = 80;
// 建構 HTTP 請求標頭
$request = "POST " . $URL_Info["path"] . " HTTP/1.1\r\n";
$request .= "Host: " . $URL_Info["host"] . "\r\n";
$request .= "Referer: $referrer\r\n";
$request .= "Content-type: application/x-www-form-urlencoded\r\n";
$request .= "Content-length: " . strlen($data_string) . "\r\n";
$request .= "Connection: close\r\n";
$request .= "\r\n";
$request .= $data_string . "\r\n";
// 發送請求
$fp = fsockopen($URL_Info["host"], $URL_Info["port"]);
fputs($fp, $request);
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
fclose($fp);
echo $result;
?>
替代方案:現成類庫
- Snoopy:SourceForge - 模擬瀏覽器功能完整
- HTTP_Request2 (PEAR):PEAR - 物件導向、支援 HTTPS、Proxy
- Guzzle:現代 PHP HTTP Client,支援非同步、PSR-7、Middleware
選擇建議
| 場景 | 推薦方案 |
| 簡單專案、需 Cookie、HTTPS、Proxy | cURL |
| 無 cURL 擴展環境、學習 HTTP 協定 | fsockopen |
| 企業級專案、維護性、測試性 | Guzzle / HTTP_Request2 |