POST方法不起作用的原因


why POST method is not working?

我确实在跨域中发布了一些信息。我通过下面的代码实现了这一点

<?php
  function do_post_request($sendingurl, $data, $optional_headers = null) {
    $params = array(
      'http' => array(
        'method' => 'POST',
        'url' => $data
      )
    );
    if ($optional_headers !== null) {
      $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $fp = @fopen($sendingurl, 'rb', false, $ctx);
    if (!$fp) {
      throw new Exception("Problem with $sendingurl, $php_errormsg");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
      throw new Exception("Problem reading data from $sendingurl, $php_errormsg");
    }
    return $response;
  }
  $response = do_post_request('http://mag16.playtrickz.com/testing.php','http%3A%2F%2Fwww.facebook.com');
  echo $response;

但它不起作用。POST请求成功时:它将显示其值否则将显示:未找到任何数据。为什么它不起作用,以及如何使它们起作用。

以下是我如何编写您的函数:

function do_post_request($url, $data = NULL, $optional_headers = NULL) {
  // Build a body string from an array
  $content = (is_array($data)) ? http_build_query($data) : '';
  // Parse the array of headers and strip values we will be setting
  $headers = array();
  if (is_array($optional_headers)) {
    foreach ($optional_headers as $name => $value) {
      if (!in_array(strtolower($name), array('content-type', 'content-length', 'connection'))) {
        $headers[$name] = $value;
      }
    }
  }
  // Add our pre-set headers
  $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  $headers['Content-Length'] = strlen($content);
  $headers['Connection'] = 'close';
  // Build headers into a string
  $header = array();
  foreach ($headers as $name => $value) {
    if (is_array($value)) {
      foreach ($value as $multi) {
        $header[] = "$name: $multi";
      }
    } else {
      $header[] = "$name: $value";
    }
  }
  $header = implode("'r'n", $header);
  // Create the stream context
  $params = array(
    'http' => array(
      'method' => 'POST',
      'header' => $header,
      'content' => $content
    )
  );
  $ctx = stream_context_create($params);
  // Make the request
  $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在远程脚本中查找,并将其传入。您也可以传递一个附加标头的数组来发送,但函数会自动添加一个Content-TypeContent-LengthConnection标头。

所以你的请求会被这样调用:

$data = array(
  'url' => 'http://www.facebook.com/'
);
$response = do_post_request('http://mag16.playtrickz.com/testing.php', $data);
echo $response;