file_get_contens POST传值
2016-07-07 11:23
288 查看
<?php echo "<pre>"; print_r($_POST); print_r($_COOKIE); ?>
本文讲述的只是http post请求的发送,所以,目标页只是回显所收到的post和cookie
2.请求页
request.php
<? $data = array("name" => 'tim',"content" => 'test'); $data = http_build_query($data); $opts = array( 'http'=>array( 'method'=>"POST", 'header'=>"Content-type: application/x-www-form-urlencoded\r\n". "Content-length:".strlen($data)."\r\n" . "Cookie: foo=bar\r\n" . "\r\n", 'content' => $data, ) ); $cxContext = stream_context_create($opts); $sFile = file_get_contents("http://localhost/response.php", false, $cxContext); echo $sFile; ?>
这个文件首先使用stream_context_create()构造了一个http请求,然后使用file_get_contents发送出去,返回的结果是:
Array ( [name] => tim [content] => test ) Array ( [foo] => bar ) |
<?php $option = array( 'http' => array( 'method' => "POST", // 常用 POST 或者 GET 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*", // Header 域内容,用于定义如 Cookie 之类的信息 'content' => "domain=www.kalvin.cn&author=kalvin", // POST 时提交的内容 ) ); $xoption = stream_context_create($option); // 生成请求所用的头信息 echo $str = file_get_contents("http://www.kalvin.cn", false, $xoption); // 执行请求 print_r($http_response_header); // 显示返回的头信息 ?>
因为要用php去向我的虚拟主机管理系统发送开通空间等的请求,需要Post传值,由于开通空间过程很慢,同时需要延时处理。以下找到了一下file_get_contents的超时处理,网上有人用2个方法解决:
在使用file_get_contents函数的时候,经常会出现超时的情况,在这里要通过查看一下错误提示,看看是哪种错误,比较常见的是读取超时,这种情况大家可以通过一些方法来尽量的避免或者解决。这里就简单介绍两种:
一、增加超时的时间限制
这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。
我一开始以为set_time_limit也能影响到file_get_contents,后来经测试,是无效的。真正的修改file_get_contents延时可以用resource $context的timeout参数:
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>60,
)
);
$context = stream_context_create($opts);
$html =file_get_contents('http://www.example.com', false, $context);
fpassthru($fp);
二、一次有延时的话那就多试几次
有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++;
以上方法对付超时已经OK了。那么Post呢?细心点有人发现了'method'=>"GET", 对!是不是能设置成post呢?百度找了下相关资料,还真可以!而且有人写出了山寨版的post传值函数,如下:
function Post($url, $post = null)
{
$context = array();
if (is_array($post))
{
ksort($post);
$context['http'] = array
(
'timeout'=>60,
'method' => 'POST',
'content' => http_build_query($post, '', '&'),
);
}
return file_get_contents($url, false, stream_context_create($context));
}
$data = array
(
换成你自己数组的值
);
$arr = post('https://api.weibo.com/oauth2/access_token', $data);
$tt=json_decode($arr,true);
相关文章推荐
- 面试题23:二叉树层序遍历
- window.location.href url含中文服务器收到乱码问题解决
- Android 中文件的操作
- Android 中文件的操作
- Android 中文件的操作
- Android 中文件的操作
- Android 笔记
- mysql获取成绩排名
- hdu:1305
- jQuery on()方法绑定动态元素的点击事件无响应的解决办法
- TabLayout实现ViewPager指示器
- linux的存储管理:硬盘、分区及文件系统
- 实训的第一次考核项目 基于socket 的客户与服务端 在线购物管理系统
- 各位转载本人原创文章的亲们,请附带原文章网址来源好吗?
- 谈Java中的hashcode方法
- Linux(Centos7.0)下HelixServer的环境搭建
- 如何使用Dockerfile构建镜像
- POJ 2559 Largest Rectangle in a Histogram
- 【编程马拉松】【023-换零钱】
- linux命令之grep