有時候,我們需要在服務(wù)器端模擬 POST/GET 等請求,也就是在 PHP 程序中去實現(xiàn)模擬,改怎么做到呢?或者說,在 PHP 程序里,給你一個數(shù)組,如何將這個數(shù)組 POST/GET 到另外一個地址呢?當(dāng)然,使用 CURL 很容易辦到,那么如果不使用 CURL 庫,又該怎么辦呢?其實,在 PHP 里已經(jīng)有相關(guān)的函數(shù)實現(xiàn)了,這個函數(shù)就是接下來要講的 stream_context_create()。
直接 show you the code,這是最好的方法:
05 | 'name' => 'nowa magic' ); |
07 | $data = http_build_query( $data ); |
09 | //$postdata = http_build_query($data); |
13 | 'header' => 'Content-type:application/x-www-form-urlencoded' , |
15 | //'timeout' => 60 * 60 // 超時時間(單位:s) |
20 | $context = stream_context_create( $options ); |
21 | $result = file_get_contents ( $url , false, $context ); |
http://www./test2.php 的代碼為:
運行結(jié)果為:
一些要點講解:
1. 以上程序用到了 http_build_query() 函數(shù),如果需要了解,可以參看 PHP函數(shù)補完:http_build_query()構(gòu)造URL字符串。
2. stream_context_create() 是用來創(chuàng)建打開文件的上下文件選項的,比如用POST訪問,使用代理,發(fā)送header等。就是
創(chuàng)建一個流,再舉一個例子吧:
01 | $context = stream_context_create( array ( |
04 | 'header' => sprintf( "Authorization: Basic %s\r\n" , base64_encode ( $username . ':' . $password )). |
05 | "Content-type: application/x-www-form-urlencoded\r\n" , |
06 | 'content' => http_build_query( array ( 'status' => $message )), |
3. stream_context_create創(chuàng)建的上下文選項即可用于流(stream),也可用于文件系統(tǒng)(file system)。對于像 file_get_contents、file_put_contents、readfile直接使用文件名操作而沒有文件句柄的函數(shù)來說更有用。stream_context_create增加header頭只是一部份功能,還可以定義代理、超時等。這使得訪問web的功能不弱于curl。
4. stream_context_create() 作用:創(chuàng)建并返回一個文本數(shù)據(jù)流并應(yīng)用各種選項,可用于fopen(),file_get_contents()等過程的超時設(shè)置、代理服務(wù)器、請求方式、頭信息設(shè)置的特殊過程。
5. stream_context_create 還能通過增加 timeout 選項解決file_get_contents超時處理:
07 | //創(chuàng)建數(shù)據(jù)流上下文 |
08 | $context = stream_context_create( $opts ); |
10 | $html = file_get_contents ( 'http://www.' , false, $context ); |
12 | //fopen輸出文件指針處的所有剩余數(shù)據(jù): |
13 | //fpassthru($fp); //fclose()前使用 |
延伸閱讀此文章所在專題列表如下: - PHP函數(shù)補完:get_magic_quotes_gpc()
- PHP函數(shù)補完:error_reporting()
- PHP函數(shù)補完:preg_match()
- PHP函數(shù)補完:urlencode()
- PHP函數(shù)補完:array_multisort()
- PHP函數(shù)補完:array_splice()
- PHP函數(shù)補完:isset()
- PHP函數(shù)補完:getenv()
- PHP函數(shù)補完:header()
- PHP函數(shù)補完:mysql_num_rows()
- PHP函數(shù)補完:list()
- PHP函數(shù)補完:mysql_query()
- PHP函數(shù)補完:mysql_fetch_array()
- PHP函數(shù)補完:number_format()
- PHP函數(shù)補完:explode()
- PHP函數(shù)補完:call_user_func()
- PHP函數(shù)補完:ImageCopyResamples()
- PHP函數(shù)補完:import_request_variables()
- PHP函數(shù)補完:parse_url()
- PHP函數(shù)補完:移除HTML標(biāo)簽strip_tags()
- PHP函數(shù)補完:輸出數(shù)組結(jié)構(gòu)與內(nèi)容var_dump()
- PHP函數(shù)補完:var_export()
- PHP函數(shù)補完:判斷變量是否為數(shù)字is_numeric()
- PHP函數(shù)補完:session_name()
- PHP函數(shù)補完:session_id()
- PHP函數(shù)補完:nl2br()與nl2p()函數(shù)
- PHP函數(shù)補完:shuffle()取數(shù)組若干個隨機元素
- PHP函數(shù)補完:http_build_query()構(gòu)造URL字符串
- PHP函數(shù)補完:stream_context_create()模擬POST/GET
|