使用数组处理HTTP Post(无cURL) [英] Processing HTTP Post with Array (no cURL)

查看:137
本文介绍了使用数组处理HTTP Post(无cURL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function do_post_request($url, $data, $optional_headers = null)
{
  $params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
 if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }
  return $response;
}

POST数组:

$postdata = array( 
    'send_email' => $_REQUEST['send_email'], 
    'send_text' => $_REQUEST['send_text']);

如何将单个数组元素添加到单个PHP var?

How can I get individual array element to individual PHP var?

POST数据处理器页面的一部分:

Part of a page of POST data processor:

...
$message = $_REQUEST['postdata']['send_text'];
...

什么是错误的?

推荐答案

试试这个:

在客户端:

function do_post_request ($url, $data, $headers = array()) {
  // Turn $data into a string
  $dataStr = http_build_query($data);
  // Turn headers into a string
  $headerStr = '';
  foreach ($headers as $key => $value) if (!in_array(strtolower($key),array('content-type','content-length'))) $headerStr .= "$key: $value\r\n";
  // Set standard headers
  $headerStr .= 'Content-Length: '.strlen($data)."\r\nContent-Type: application/x-www-form-urlencoded"
  // Create a context
  $context = stream_context_create(array('http' => array('method' => 'POST', 'content' => $data, 'header' => $headerStr)));
  // Do the request and return the result
  return ($result = file_get_contents($url, FALSE, $context)) ? $result : FALSE;
}

$url = 'http://sub.domain.tld/file.ext';
$postData = array( 
  'send_email' => $_REQUEST['send_email'], 
  'send_text' => $_REQUEST['send_text']
);
$extraHeaders = array(
  'User-Agent' => 'My HTTP Client/1.1'
);

var_dump(do_post_request($url, $postData, $extraHeaders));

在服务器端:

print_r($_POST);
/*
  Outputs something like:
    Array (
      [send_email] => Some Value
      [send_text] => Some Other Value
    )
*/

$message = $_POST['send_text'];
echo $message;
// Outputs something like: Some Other Value

这篇关于使用数组处理HTTP Post(无cURL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆