Chinaunix首页 | 论坛 | 博客
  • 博客访问: 328610
  • 博文数量: 121
  • 博客积分: 2771
  • 博客等级: 少校
  • 技术积分: 705
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-01 12:44
文章分类

全部博文(121)

文章存档

2011年(121)

分类: 系统运维

2011-04-07 23:50:35

curl是一个很好很强大的工具,但PHP并不自带这个类库,而且我们只是要实现POST方法,杀鸡焉用牛刀。纯PHP就能实现,还没有兼容性的问题。

这个函数是,有了它我们就可以非常方便地实现POST提交了。下面是一个可以直接使用的函数

  1. /**
  2.  * @param $url string | 要提交的URL地址
  3.  * @param $data array | 要提交的POST数据
  4.  * @param $optional_headers | 基本上这个不用理会
  5.  */
  6. function post_request($url, $data, $optional_headers = null)
  7. {
  8.  $params = array('http' => array(
  9.   'method' => 'POST',
  10.   'content' => http_build_query($data),
  11.   ));
  12.  if ($optional_headers !== null)
  13.  {
  14.   $params['http']['header'] = $optional_headers;
  15.  }
  16.  $ctx = stream_context_create($params);
  17.  $fp = @fopen($url, 'rb', false, $ctx);
  18.  if (!$fp)
  19.  {
  20.     throw new Exception("Problem with $url");
  21.  }
  22.  $response = @stream_get_contents($fp);
  23.  if ($response === false)
  24.  {
  25.     throw new Exception("Problem reading data from $url");
  26.  }
  27.  return $response;
  28. }

很简单吧,你或许会问,stream_context_create这个函数的参数是从何而来的,有一份详细的说明。

我们也可以通过stream_context_create这个函数来实现代理功能。代理的重要性就不用多说了吧

  1. <?php
  2. $opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
  3. $context = stream_context_create($opts);
  4. $data = file_get_contents('', false, $context);
  5. echo $data;
  6. ?>

甚至可以使用它来上传文件

  1. $fileHandle = fopen("someImage.jpg", "rb");
  2. $fileContents = stream_get_contents($fileHandle);
  3. fclose($fileHandle);

  4. $params = array(
  5.   'http' => array
  6.   (
  7.    'method' => 'POST',
  8.    'header'=>"Content-Type: multipart/form-data\r\n",
  9.    'content' => $fileContents
  10.   )
  11. );
  12. $url = "";
  13. $ctx = stream_context_create($params);
  14. $fp = fopen($url, 'rb', false, $ctx);

  15. $response = stream_get_contents($fp);

这下应该不用再为POST发愁了吧

阅读(1830) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~