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

stream.php

<?php
$data = array(
'foo'=>'bar',
'baz'=>'boom',
'site'=>'www.nowamagic.net',
'name'=>'nowa magic'); $postData = http_build_query($data); $options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postData
)
); $url = "http://127.0.0.1/test.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context); echo $result;//输出返回值

test.php

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

结果:

Array
(
[foo] => bar
[baz] => boom
[site] => www.nowamagic.net
[name] => nowa magic
) 另外,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://127.0.0.1/test.php', false, $context);

最新文章

  1. Node.js之sails框架
  2. SpringMVC注解汇总(一)-定义
  3. MQTT——服务器搭建(一)
  4. I/O优化篇
  5. JQuery text()、html() 以及 val()
  6. Parallel的陷阱
  7. 巨大bug
  8. System.Data.OracleClient 需要 Oracle 客户端软件 8.1.7 或更高版本
  9. 判断对象是不是Vector
  10. BZOJ 1649: [Usaco2006 Dec]Cow Roller Coaster( dp )
  11. haproxy timeout server 46000 后台超时时间
  12. contextmenu
  13. JVM相关知识(1)
  14. MyBatis 框架笔记
  15. Linux学习——shell编程之环境变量配置文件
  16. c语言的extern与static与递归
  17. Java多线程,判断其他线程是否结束的方法
  18. Android Studio教程07-Fragment的使用
  19. VM磁盘映射共享方法,要求文件系统必须一致
  20. Bitmap每个像素值由指定的掩码决定

热门文章

  1. 使用adb命令启查看已安装的Android应用的versionCode、versionName
  2. appium+python自动化-adb shell模拟点击事件(input tap)
  3. 【LeetCode】Powerful Integers(强整数)
  4. C语言常见的函数调用
  5. SQLSERVER 差异备份、全备份
  6. tomcat的管理(manager)报错403
  7. 自动化运维之shell通配符,转义符,和元字符(二)
  8. Python 频繁读取Mysql相关问题
  9. BZOJ 1294 [SCOI2009]围豆豆Bean ——计算几何
  10. BZOJ 2190 [SDOI2008]仪仗队 ——Dirichlet积