This article mainly introduces the method of PHP using stream_context_create() to simulate POST/GET requests. It analyzes the principle of stream_context_create to simulate POST/GET requests in detail in the form of examples, the usage method and related precautions. Friends in need can Refer to the next
Sometimes, we need to simulate POST/GET and other requests on the server side, that is, to implement the simulation in the PHP program. How to do it? In other words, in a PHP program, if you are given an array, how do you POST/GET this array to another address? Of course, it's easy to do it using CURL, but what if you don't use the CURL library? In fact, there is already a related function implemented in PHP, and this function is stream_context_create() that I will talk about next.
Show you the code directly, this is the best way:
$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:/ The code of /localhost/test2.php is:
$data = $_POST; echo ''; print_r( $data ); echo '';Copy after login
The running result is:
Array ( [foo] => bar [baz] => boom [site] => localhost [name] => nowa magic )
Some key points to explain:
1. The above program uses the http_build_query() function. If you need to know more, you can refer to the previous article "PHP uses http_build_query()" Method to construct URL string》.
2. stream_context_create() is used to create context options for opening files, such as accessing with POST, using a proxy, sending headers, etc. Just create a stream. Let’s give another example:
$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);
##
$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()前使用
Related recommendations:
phpQuick sorting principle, implementation method and example analysis
##PHP MVC framework skymvc supports multiple file upload implementation methods
The above is the detailed content of PHP uses stream_context_create() to simulate POST/GET request method and example analysis. For more information, please follow other related articles on the PHP Chinese website!