PHP實用函數:stream_context_create()類比POST/GET,
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'=>'www.lai18.com', 'name'=>'lai18'); $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://www.lai18.net/";$context = stream_context_create($options);$result = file_get_contents($url, false, $context);echo $result;
http://www.lai18.com 的代碼為:
$data = $_POST;echo '<pre>';print_r( $data );echo '</pre>';
運行結果為:
Array( [foo] => bar [baz] => boom [site] => www.lai18.com [name] => lai18)
一些要點講解(參考:
http://www.lai18.com/content/425476.html):
1. 以上程式用到了 http_build_query() 函數,如果需要瞭解,可以參看 stream),也可用於檔案系統(file system)。對於像 file_get_contents、file_put_contents、readfile直接使用檔案名稱操作而沒有檔案控制代碼的函數來說更有用。stream_context_create增加header頭只是一部份功能,還可以定義代理、逾時等。這使得訪問web的功能不弱於curl。
4. stream_context_create() 作用:建立並返回一個文本資料流並應用各種選項,可用於fopen(),file_get_contents()等過程的逾時設定、Proxy 伺服器、請求方式、頭資訊設定的特殊過程。
5. stream_context_create 還能通過增加 timeout 選項解決file_get_contents逾時處理:
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ));//建立資料流上下文$context = stream_context_create($opts);$html =file_get_contents('http://www.lai18.com', false, $context);//fopen輸出檔案指標處的所有剩餘資料://fpassthru($fp); //fclose()前使用延伸閱讀此文章所在專題列表如下:
1PHP函數補完:get_magic_quotes_gpc()
2PHP函數補完:error_reporting()
3PHP函數補完:array_splice()
4PHP函數補完:isset()
5PHP函數補完:array_multisort()
6PHP函數補完:urlencode()
7PHP函數補完:preg_match()
8PHP函數補完:header()
9PHP函數補完:getenv()
10PHP函數補完:list()
11PHP函數補完:mysql_num_rows()
12PHP函數補完:explode()
13PHP函數補完:mysql_fetch_array()
14PHP函數補完:number_format()
15PHP函數補完:mysql_query()
16PHP函數補完:empty()
17PHP函數補完:call_user_func()
18PHP函數補完:parse_url()
19PHP函數補完:import_request_variables()
20PHP函數補完:ImageCopyResamples()
21PHP函數補完:移除HTML標籤strip_tags()
22PHP函數補完:輸出數組結構與內容var_dump()
23PHP函數補完:var_export()
24PHP函數補完:判斷變數是否為數字is_numeric()
25PHP函數補完:http_build_query()構造URL字串
26PHP實用函數手冊:stream_context_create()類比POST/GET
27PHP函數補完:shuffle()取數組若干個隨機元素
28PHP函數補完:session_id()
29PHP函數補完:nl2br()與nl2p()函數
30PHP函數補完:session_name()
31php計劃任務之ignore_user_abort函數實現方法
32PHP中error_log()函數的使用方法
33PHP實用函數-array_change_key_case()將數組的鍵轉換大小寫
34PHP實用函數-function_exists()檢測函數是否已定義
35PHP實用函數-array_intersect()計算兩個或多個數組的交集
36PHP實用函數-array_diff()計算數組間的差集
37PHP實用函數-compact()將已知變數轉換成數組
38PHP實用函數-extract()將數群組轉換成對應鍵值對變數
39PHP實用函數-array_count_values()統計數組中元素出現的次數
40PHP實用函數-getopt()從命令列參數列表中擷取選項
41PHP實用函數 String函數分類
42使用PHP內建的filter函數進行資料校正