首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 模擬 POST 請求兩大方法:cURL 與 fsockopen 完整實作

     編輯:PHP 綜合知識

方法一: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、ProxycURL
無 cURL 擴展環境、學習 HTTP 協定fsockopen
企業級專案、維護性、測試性Guzzle / HTTP_Request2
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved