file_get_contens POST传值

<?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  
 )

所以上可以看出,只要你了解http协议,完全可以使用这两个函数构造出所有正常的http请求,比如代理,断点续传等…

<?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);

posted @ 2016-07-07 11:23  心浩宇  阅读(836)  评论(0编辑  收藏  举报