《PHP編程:PHP使用stream_context_create()模擬POST/GET請求的方法》要點:
本文介紹了PHP編程:PHP使用stream_context_create()模擬POST/GET請求的方法,希望對您有用。如果有疑問,可以聯系我們。
本文實例講述了PHP使用stream_context_create()模擬POST/GET哀求的方法.分享給大家供大家參考,具體如下:PHP應用
有時候,我們需要在服務器端模擬 POST/GET 等哀求,也就是在 PHP 程序中去實現模擬,改怎么做到呢?或者說,在 PHP 程序里,給你一個數組,如何將這個數組 POST/GET 到另外一個地址呢?當然,使用 CURL 很容易辦到,那么如果不使用 CURL 庫,又該怎么辦呢?其實,在 PHP 里已經有相關的函數實現了,這個函數就是接下來要講的 stream_context_create().PHP應用
直接 show you the code,這是最好的辦法:PHP應用
$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 的代碼為:PHP應用
$data = $_POST; echo '<pre>'; print_r( $data ); echo '</pre>';
運行結果為:PHP應用
Array ( [foo] => bar [baz] => boom [site] => localhost [name] => nowa magic )
一些要點講解:PHP應用
1. 以上程序用到了 http_build_query() 函數,如果需要了解,可以參看?前面一篇《PHP使用http_build_query()構造URL字符串的辦法》.PHP應用
2. stream_context_create() 是用來創建打開文件的上下文件選項的,比如用POST拜訪,使用代理,發送header等.就是 創建一個流,再舉一個例子吧:PHP應用
$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.PHP應用
4. stream_context_create() 作用:創建并返回一個文本數據流并應用各種選項,可用于fopen(),file_get_contents()等過程的超時設置、代理服務器、哀求方式、頭信息設置的特殊過程.PHP應用
5. stream_context_create 還能通過增加 timeout 選項辦理file_get_contents超時處理:PHP應用
$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程序設計有所贊助.PHP應用
歡迎參與《PHP編程:PHP使用stream_context_create()模擬POST/GET請求的方法》討論,分享您的想法,維易PHP學院為您提供專業教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/6984.html