码迷,mamicode.com
首页 > Web开发 > 详细

PHP函数:stream_context_create()模拟POST/GET

时间:2015-06-26 14:59:07      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:php模拟postget请求

有时候,我们需要在服务器端模拟 POST/GET 等请求,也就是在 PHP 程序中去实现模拟,改怎么做到呢?或者说,在 PHP 程序里,给你一个数组,如何将这个数组 POST/GET 到另外一个地址呢?当然,使用 CURL 很容易办到,那么如果不使用 CURL 库,又该怎么办呢?其实,在 PHP 里已经有相关的函数实现了,这个函数就是接下来要讲的 stream_context_create()。


直接 show you the code,这是最好的方法

<?php
$data = array(
	'foo'=>'bar', 
	'baz'=>'boom', 
	'site'=>'www.example.net', 
	'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://127.0.0.1/test2.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;
?>


test2.php 的代码为:

<?php 
$data = $_POST;
echo '<pre>';
print_r( $data );
echo '</pre>';
?>

运行结果为:

Array
(
    [foo] => bar
    [baz] => boom
    [site] => www.example.net
    [name] => nowa magic
)

PHP函数:stream_context_create()模拟POST/GET

标签:php模拟postget请求

原文地址:http://blog.csdn.net/phpfenghuo/article/details/46650003

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!