abstract:本文實(shí)例講述了PHP使用stream_context_create()模擬POST/GET請求的方法。分享給大家供大家參考,具體如下:有時(shí)候,我們需要在服務(wù)器端模擬 POST/GET 等請求,也就是在 PHP 程序中去實(shí)現(xiàn)模擬,改怎么做到呢?或者說,在 PHP 程序里,給你一個(gè)數(shù)組,如何將這個(gè)數(shù)組 POST/GET 到另外一個(gè)地址呢?當(dāng)然,使用 CURL 很容易辦到,那么如果不使用 CURL 庫,
本文實(shí)例講述了PHP使用stream_context_create()模擬POST/GET請求的方法。分享給大家供大家參考,具體如下:
有時(shí)候,我們需要在服務(wù)器端模擬 POST/GET 等請求,也就是在 PHP 程序中去實(shí)現(xiàn)模擬,改怎么做到呢?或者說,在 PHP 程序里,給你一個(gè)數(shù)組,如何將這個(gè)數(shù)組 POST/GET 到另外一個(gè)地址呢?當(dāng)然,使用 CURL 很容易辦到,那么如果不使用 CURL 庫,又該怎么辦呢?其實(shí),在 PHP 里已經(jīng)有相關(guān)的函數(shù)實(shí)現(xiàn)了,這個(gè)函數(shù)就是接下來要講的 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 // 超時(shí)時(shí)間(單位: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>';
運(yùn)行結(jié)果為:
Array ( [foo] => bar [baz] => boom [site] => localhost [name] => nowa magic )
一些要點(diǎn)講解:
1. 以上程序用到了 http_build_query() 函數(shù),如果需要了解,可以參看 前面一篇《PHP使用http_build_query()構(gòu)造URL字符串的方法》。
2. stream_context_create() 是用來創(chuàng)建打開文件的上下文件選項(xiàng)的,比如用POST訪問,使用代理,發(fā)送header等。就是 創(chuàng)建一個(gè)流,再舉一個(gè)例子吧:
$context = stream_context_create(array( 'http' => array( 'method' => 'POST', 'header' => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)). "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query(array('status' => $message)), 'timeout' => 5, ), )); $ret = file_get_contents('http://twitter.com/statuses/UPDATE.xml', false, $context);
3. stream_context_create創(chuàng)建的上下文選項(xiàng)即可用于流(stream),也可用于文件系統(tǒng)(file system)。對于像 file_get_contents、file_put_contents、readfile直接使用文件名操作而沒有文件句柄的函數(shù)來說更有用。stream_context_create增加header頭只是一部份功能,還可以定義代理、超時(shí)等。這使得訪問web的功能不弱于curl。
4. stream_context_create() 作用:創(chuàng)建并返回一個(gè)文本數(shù)據(jù)流并應(yīng)用各種選項(xiàng),可用于fopen(),file_get_contents()等過程的超時(shí)設(shè)置、代理服務(wù)器、請求方式、頭信息設(shè)置的特殊過程。
5. stream_context_create 還能通過增加 timeout 選項(xiàng)解決file_get_contents超時(shí)處理:
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); //創(chuàng)建數(shù)據(jù)流上下文 $context = stream_context_create($opts); $html =file_get_contents('http://localhost', false, $context); //fopen輸出文件指針處的所有剩余數(shù)據(jù): //fpassthru($fp); //fclose()前使用
更多關(guān)于PHP使用stream_context_create()模擬POST/GET請求的方法請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)其他文章!