php函数file_get_contents(二)

上篇说到我们说到设置file_get_contents超时时间用到了 stream_context_create方法,那么这个方法到底是什么呢?

查了下资料, stream_context_create创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。这样看起来功能就强大了,不仅仅可以设置超时时间,还可以设置代理服务器,请求方式和头信息,下面我们就测试下吧:
request.php请求页面负责发起请求:
 1 <?php
 2  $data = array("name" => 'test_name',"content" => 'test_con');
 3  $data = http_build_query($data);
 4  $opts = array(
 5    'http'=>array(
 6      'method'=>"POST",
 7      'header'=>"Content-type: application/x-www-form-urlencoded\r\n".
 8                "Content-length:".strlen($data)."\r\n" .
 9                "Cookie: foo=bar\r\n" .
10                "\r\n",
11      'content' => $data,
12    )
13  );
14  $cxContext = stream_context_create($opts);
15  $sFile = file_get_contents("http://127.0.0.1/reponse.php", false, $cxContext);   
16  echo $sFile;
17 ?>

 

reponse.php被请求的页面:
<?php
var_dump($_POST);
var_dump($_COOKIE);
?>

 

运行之后的结果为:
string(132) "array(2) { ["content"]=> string(8) "test_con" ["name"]=> string(9) "test_name" } array(1) { ["foo"]=> string(3) "bar" } "  
说明file_get_contents可以post数据和cookie数据到目标url,并获得内容。
posted @ 2014-03-18 13:56  scofi  阅读(778)  评论(0编辑  收藏  举报