PHP模擬http請求的方法詳解

2022-09-29 22:15:26 字數 2932 閱讀 9553

方法一:利用php的socket程式設計來直接給介面傳送資料來模擬post的操作。

建立兩個檔案post.php,getpost.php

post.php內容如下:

<?php $flag = 0;

$params = '';

$errno = '';

$errstr = '';

//要post的資料

$ar** = array(

'var1'=>'abc',

'var2'=>'how are you , my friend??');

//構造要post的字串

foreach ($ar** as $key=>$value)

$params.= $key."="; $params.= urlencode($value);

$flag = 1;

} $length = strlen($params);

//程式設計客棧建立socket連線

$fp = fsockopen("localhost",81,$errno,$errstr,10) or exit($errstr."--->".$errno);

//構造post請求的頭

//新增post的字串

$header .= $params."\r\n";

//傳送post的資料

fputs($fp,$header);

$inheader = 1;

while (!feof($fp))

if ($inheader == 0)

}fclose($fp);

?>

getpost.php的內容如下:

<?php echo "this is the data posted";

echo "";

print_r($_request);

ec程式設計客棧ho "";

?>

lhwjcxdam

結果輸出:

this is the data posted

array

( [var1] => abc

[var2] => how are you , my friend??

)以上**在本機81埠下已經通過測試。

方法二:使用php的curl擴充套件或httpclient.class.php類,這兩個非常類似,下面簡單的列出curl的實現**。

兩個檔案post2.php和getpost2.php

post2.php的內容如下:

curl_setopt($ch, curlopt_returntransfer, 1)程式設計客棧;//不直接輸出,返回到變數

$curl_result = curl_exec($ch);

$result = explode(',', $curl_result);

curl_close($ch);

print_r($result);

?>

getpost2.php的內容如下:

<?php echo "returndata

";echo "";

print_r($_request);

echo "";

?>

結果輸出:

array ( [0] => returnd程式設計客棧ata

))方法三:這個要借助第三方類庫httpclient

可以到這裡**:

或者點選此處本站**。

PHP模擬http請求

方法一 利用php的socket程式設計來直接給介面傳送資料來模擬post的操作。建立兩個檔案post.php,getpost.php post.php內容如下 flag 0 params errno errstr 要post的資料 argv array var1 abc var2 how are ...

php模擬http請求

http請求有get,post。php傳送http請求有三種方式 我所知道的有三種,有其他的告訴我 file get contents 詳情見 curl傳送請求。fsocket傳送。下面說使用curl傳送。首先環境需要配置好curl元件。1 2 3 4 5 6 7 8 9 10 在windows中讓...

php 模擬http請求

原文 guzzlehttp模擬表單提交 並用nodejs接受資料 return response js接收資料 const bodyparser require body parser server.listen 80 use bodyparser.urlencoded use bodyparser...