首页 > PHP > 使用file_get_contents提交http post

使用file_get_contents提交http post

2009年9月4日 发表评论 阅读评论

以前使用curl获取需要登陆内容的文章,但其实,自5.0开始,使用file_get_contents就可以完成.(前提是开启了allow_url_fopen),下面以一个简单的例子说明一下:
1.先看一下目标网页(假设是http://localhost/response.php)
response.php

1
2
3
4
5
<?php  
 echo "<pre>";  
 print_r($_POST);  
 print_r($_COOKIE);  
 ?>

本文讲述的只是http post请求的发送,所以,目标页只是回显所收到的post和cookie

2.请求页
request.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?
 $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发送出去,返回的结果是:

1
2
3
4
5
6
7
8
9
 Array
 (  
     [name] => tim  
     [content] => test  
 )  
 Array  
 (  
     [foo] => bar  
 )

所以上可以看出,只要你了解http协议,完全可以使用这两个函数构造出所有正常的http请求,比如代理,断点续传等…
对照之前的关于curl的文章,就可以用来取得需要用户验证的内容了.

本文来源:http://www.phpec.com/?action=show&id=37

本文地址:http://www.etang.info/php-it/file_get_contents-http-post.html

文章来源:亿唐网

原创文章,转载请注明以上版权信息,亿唐网感谢您的理解与支持!

分类: PHP 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.
您必须在 登录 后才能发布评论.