使用file_get_contents提交http post

PHPec 2009-10-21 22:17:32 累计浏览 7,803 次

    我曾经发过一篇讲使用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. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,702)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,568)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,821)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,719)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 13,274)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,950)
  7. Redis消息队列的若干实现方式 (累计阅读 12,536)
  8. 到底什么是MVC? (累计阅读 12,385)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 12,222)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,972)