【问题标题】:Processing HTTP Post with Array (no cURL)使用数组处理 HTTP Post(无 cURL)
【发布时间】:2011-10-19 14:39:48
【问题描述】:
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?

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

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

怎么了?

【问题讨论】:

  • 你能试着澄清一下你遇到的问题吗?您是否收到任何错误消息?还是与另一端的脚本有关,即您要向其发送数据的页面的问题?
  • POST 数据处理器什么也没显示,它什么也没收到。
  • ...如果你print_r($_REQUEST);,你会得到什么?

标签: php arrays http-post


【解决方案1】:

试试这个:

在客户端:

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

【讨论】:

  • 非常感谢。错误很简单。
猜你喜欢
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 2015-10-13
  • 2010-12-08
  • 2015-10-14
相关资源
最近更新 更多