首頁  >  文章  >  後端開發  >  PHP使用stream_context_create()來模擬POST/GET請求的方法

PHP使用stream_context_create()來模擬POST/GET請求的方法

高洛峰
高洛峰原創
2017-01-06 15:10:221467瀏覽

本文實例講述了PHP使用stream_context_create()模擬POST/GET請求的方法。分享給大家供大家參考,具體如下:

有時候,我們需要在伺服器端模擬 POST/GET 等請求,也就是在 PHP 程式中去實現模擬,改怎麼做呢?或者說,在 PHP 程式裡,給你一個數組,如何將這個數組 POST/GET 到另一個位址?當然,使用 CURL 很容易辦到,那麼如果不使用 CURL 庫,又該怎麼辦呢?其實,在 PHP 裡已經有相關的函數實作了,這個函數就是接下來要講的 stream_context_create()。

直接show you the code,這是最好的方法:

$data = array(
    'foo'=>'bar', 
    'baz'=>'boom', 
    'site'=>'localhost', 
    'name'=>'nowa magic'); 
$data = http_build_query($data); 
//$postdata = http_build_query($data);
$options = array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencoded',
        'content' => $data
        //'timeout' => 60 * 60 // 超时时间(单位:s)
    )
);
$url = "http://localhost/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;

直接show you the code,這是最好的方法:

$data = $_POST;
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r( $data );
echo &#39;
';

http://localhost/test2.php 的代碼為:

Array
(
  [foo] => bar
  [baz] => boom
  [site] => localhost
  [name] => nowa magic
)

   

重點解說:

1. 以上程式用到了http_build_query() 函數,如果需要了解,可以參考 前面一篇《PHP使用http_build_query()建構URL字串的方法》。

2. stream_context_create() 是用來創建打開文件的上下文件選項的,例如用POST訪問,使用代理,發送header等。就是 建立一個流,再舉一個例子:

$context = stream_context_create(array(
    &#39;http&#39; => array(
        &#39;method&#39; => &#39;POST&#39;,
        &#39;header&#39; => sprintf("Authorization: Basic %s\r\n", base64_encode($username.&#39;:&#39;.$password)).
        "Content-type: application/x-www-form-urlencoded\r\n",
        &#39;content&#39; => http_build_query(array(&#39;status&#39; => $message)),
        &#39;timeout&#39; => 5,
    ),
));
$ret = file_get_contents(&#39;http://twitter.com/statuses/update.xml&#39;, false, $context);

   

3. stream_context_create建立的上下文選項即可用於流(stream),也可用於檔案系統(file system)。對於像 file_get_contents、file_put_contents、readfile直接使用檔案名稱操作而沒有檔案句柄的函數來說更有用。 stream_context_create增加header頭只是一部份功能,還可以定義代理、逾時等。這使得存取web的功能不弱於curl。

4. stream_context_create() 作用:建立並傳回一個文字資料流並套用各種選項,可用於fopen(),file_get_contents()等過程的逾時設定、代理伺服器、請求方式、頭資訊設定的特殊流程。

5. stream_context_create 也可以透過增加 timeout 選項解決file_get_contents逾時處理:

$opts = array(
  &#39;http&#39;=>array(
  &#39;method&#39;=>"GET",
  &#39;timeout&#39;=>60,
 )
);
//创建数据流上下文
$context = stream_context_create($opts);
$html =file_get_contents(&#39;http://localhost&#39;, false, $context);
//fopen输出文件指针处的所有剩余数据:
//fpassthru($fp); //fclose()前使用

   

更多PHP使用stream_context_create(

更多PHP使用stream_context_create(3)要求模擬相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn