天天看點

使用stream_context_create()模拟POST/GET請求的方法

  有時候,我們需要在伺服器端模拟 POST/GET 等請求,也就是在 PHP 程式中去實作模拟。

  或者說,在 PHP 程式裡,給你一個數組,如何将這個數組 POST/GET 到另外一個位址呢?當然,使用 CURL 很容易辦到,那麼如果不使用 CURL 庫,又該怎麼辦呢?其實,在 PHP 裡已經有相關的函數實作了,這個函數就是接下來要講的 stream_context_create()。代碼如下:

$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;      

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

$data = $_POST;
echo '<pre>';
print_r( $data );
echo '</pre>';      

運作結果為:

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