为什么POST方法不起作用?

时间:2012-03-06 11:31:06

标签: php

我已经在跨域发布了一些信息。而我正通过以下代码实现这一点

<?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请求:它将显示其值 否则会显示:发现。 为什么它不工作以及如何使它们工作。

1 个答案:

答案 0 :(得分:0)

以下是我编写函数的方法:

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查看远程脚本并将其传入的数组。您还可以传递一组其他标头以进行发送,但该函数将自动添加{{ 1}},Content-TypeContent-Length标题。

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

Connection