PHP使用stream_context_create()類比POST/GET請求的方法,streamcontext
本文執行個體講述了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'=>'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 '';print_r( $data );echo '
';
運行結果為:
Array( [foo] => bar [baz] => boom [site] => localhost [name] => nowa magic)
一些要點講解:
1. 以上程式用到了 http_build_query() 函數,如果需要瞭解,可以參看 前面一篇《PHP使用http_build_query()構造URL字串的方法》。
2. stream_context_create() 是用來建立開啟檔案的上下檔案選項的,比如用POST訪問,使用代理,發送header等。就是 建立一個流,再舉一個例子吧:
$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建立的上下文選項即可用於流(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://localhost', false, $context);//fopen輸出檔案指標處的所有剩餘資料://fpassthru($fp); //fclose()前使用
更多關於PHP相關內容感興趣的讀者可查看本站專題:《PHP運算與運算子用法總結》、《PHP網路編程技巧總結》、《PHP基本文法入門教程》、《php操作office文檔技巧總結(包括word,excel,access,ppt)》、《php日期與時間用法總結》、《php物件導向程式設計入門教程》、《php字串(string)用法總結》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧匯總》
希望本文所述對大家PHP程式設計有所協助。
您可能感興趣的文章:
- PHP stream_context_create()函數的使用樣本
- PHP stream_context_create()作用和用法分析
- php中突破基於HTTP_REFERER的防盜鏈措施(stream_context_create)
- 利用PHP fsockopen 類比POST/GET傳送資料的方法
- php自訂類fsocket類比post或get請求的方法
- 使用PHP Socket 編程類比Http post和get請求
- php中用socket類比http中post或者get提交資料的範例程式碼
- php 類比POST|GET操作實現代碼
- PHP CURL類比GET及POST函數代碼
http://www.bkjia.com/PHPjc/1117036.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1117036.htmlTechArticlePHP使用stream_context_create()類比POST/GET請求的方法,streamcontext 本文執行個體講述了PHP使用stream_context_create()類比POST/GET請求的方法。分享給大家供大...