技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> PHP --> 使用file_get_contents提交http post

使用file_get_contents提交http post

浏览:6652次  出处信息

    我曾经发过一篇讲使用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);  
?>  

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

    2.请求页

    request.php

以下是代码片段:

<?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请求,比如代理,断点续传等...

    对照之前的关于curl的文章,就可以用来取得需要用户验证的内容了.

建议继续学习:

  1. JSONP与POST方式请求    (阅读:10318)
  2. YSLOW法则中,为什么yahoo推荐用GET代替POST?    (阅读:9655)
  3. POST与GET的区别及RESTful    (阅读:6324)
  4. 如何在nginx的access log中记录post请求的参数    (阅读:3151)
  5. Ajax还是普通Post?    (阅读:2269)
  6. HTTP 的 POST 参数提交和上传的不同与 Mojolicious 的实现.    (阅读:1066)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1