有時候,我們需要在服務器端模擬 POST/GET 等請求,也就是在 PHP 程序中去實現(xiàn)模擬,改怎么做到呢?或者說,在 PHP 程序里,給你一個數(shù)組,如何將這個數(shù)組 POST/GET 到另外一個地址呢?當然,使用 CURL 很容易辦到,那么如果不使用 CURL 庫,又該怎么辦呢?其實,在 PHP 里已經(jīng)有相關的函數(shù)實現(xiàn)了,這個函數(shù)就是接下來要講的 stream_context_create()。
直接 show you the code,這是最好的方法:
01 | $data = array ( |
02 | 'foo' => 'bar' , |
03 | 'baz' => 'boom' , |
04 | 'site' => 'www.nowamagic.net' , |
05 | 'name' => 'nowa magic' ); |
06 | |
07 | $data = http_build_query( $data ); |
08 |
09 | //$postdata = http_build_query($data); |
10 | $options = array ( |
11 | 'http' => array ( |
12 | 'method' => 'POST' , |
13 | 'header' => 'Content-type:application/x-www-form-urlencoded' , |
14 | 'content' => $data |
15 | //'timeout' => 60 * 60 // 超時時間(單位:s) |
16 | ) |
17 | ); |
18 |
19 | $url = " |
20 | $context = stream_context_create( $options ); |
21 | $result = file_get_contents ( $url , false, $context ); |
22 |
23 | echo $result ; |
http://www.nowamagic.net/test2.php 的代碼為:
1 | $data = $_POST ; |
2 |
3 | echo '<pre>' ; |
4 | print_r( $data ); |
5 | echo '</pre>' ; |
運行結果為:
1 | Array |
2 | ( |
3 | [foo] => bar |
4 | [baz] => boom |
5 | [site] => www.nowamagic.net |
6 | [name] => nowa magic |
7 | ) |
一些要點講解:
1. 以上程序用到了 http_build_query() 函數(shù),如果需要了解,可以參看 PHP函數(shù)補完:http_build_query()構造URL字符串。
2. stream_context_create() 是用來創(chuàng)建打開文件的上下文件選項的,比如用POST訪問,使用代理,發(fā)送header等。就是創(chuàng)建一個流,再舉一個例子吧:
01 | $context = stream_context_create( array ( |
02 | 'http' => array ( |
03 | 'method' => 'POST' , |
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 )), |
07 | 'timeout' => 5, |
08 | ), |
09 | )); |
10 | $ret = file_get_contents ( ' |
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ù)流并應用各種選項,可用于fopen(),file_get_contents()等過程的超時設置、代理服務器、請求方式、頭信息設置的特殊過程。
5. stream_context_create 還能通過增加 timeout 選項解決file_get_contents超時處理:
01 | $opts = array ( |
02 | 'http' => array ( |
03 | 'method' => "GET" , |
04 | 'timeout' =>60, |
05 | ) |
06 | ); |
07 | //創(chuàng)建數(shù)據(jù)流上下文 |
08 | $context = stream_context_create( $opts ); |
09 |
10 | $html = file_get_contents ( ' |
11 |
12 | //fopen輸出文件指針處的所有剩余數(shù)據(jù): |
13 | //fpassthru($fp); //fclose()前使用 |
此文章所在專題列表如下: