您的位置:首页 > 理论基础 > 计算机网络

使用file_get_contents提交http post

2016-07-21 10:47 330 查看
以前使用curl获取需要登陆内容的文章,但其实,自5.0开始,使用file_get_contents就可以完成.(前提是开启了allow_url_fopen),下面以一个简单的例子说明一下:

1.先看一下目标网页(假设是http://localhost/response.php)

response.php
<?php
echo"<pre>";
print_r($_POST);
print_r($_COOKIE);
?>


本文讲述的只是httppost请求的发送,所以,目标页只是回显所收到的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
)


所以上可以看出,只要你了解http协议,完全可以使用这两个函数构造出所有正常的http请求,比如代理,断点续传等…
<?php
$option=array(
'http'=>array(
'method'=>"POST",//常用POST或者GET
'header'=>"User-Agent:Mozilla/5.0(Windows;U;WindowsNT6.0;en-US)\r\nAccept:*/*",//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传值函数,如下:

functionPost($url,$post=null)
{
$context=array();

if(is_array($post))
{
ksort($post);

$context['http']=array
(

'timeout'=>60,
'method'=>'POST',
'content'=>http_build_query($post,'','&'),
);
}

returnfile_get_contents($url,false,stream_context_create($context));
}

$data=array
(
'name'=>'test',
'email'=>'test@gmail.com',
'submit'=>'submit',
);

echoPost('http://www.yifu.info',$data);


OK,上面函数完美了,既解决了超时控制又解决了Post传值。再配合康盛的改良版RC4加密解密算法,做一个安全性很高的webservice就简单多了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  服务器 web前端 php