当前位置:首页 > PHP教程 > php函数 > 列表

php发送post请求函数分享

发布:smiling 来源: PHP粉丝网  添加日期:2020-10-19 17:33:14 浏览: 评论:0 

这篇文章主要介绍了一个php发送post请求的函数,开发中经常会用到,需要的朋友可以参考下,代码如下:

  1. function do_post_request($url, $data, $optional_headers = null) 
  2. { 
  3.  $params = array('http' => array( 
  4. 'method' => 'POST', 
  5. 'content' => $data 
  6.  )); 
  7.  if ($optional_headers !== null) { 
  8. $params['http']['header'] = $optional_headers; 
  9.  } 
  10.  $ctx = stream_context_create($params); 
  11.  $fp = @fopen($url, 'rb', false, $ctx); 
  12.  if (!$fp) { 
  13. throw new Exception("Problem with $url, $php_errormsg"); 
  14.  } //phpfensi.com 
  15.  $response = @stream_get_contents($fp); 
  16.  if ($response === false) { 
  17. throw new Exception("Problem reading data from $url, $php_errormsg"); 
  18.  } 
  19.  return $response; 
  20. } 

用法如下:

  1. //json字符串 
  2. $data = "{...}"; 
  3. //转换成数组 
  4. $data=json_decode($data,true); 
  5. $postdata = http_build_query($data); 
  6. do_post_request("http://localhost",$postdata); 

Tags: php发送post请求函数

分享到: