使用fsockopen POST到GET查询URL


Using fsockopen to POST to a GET query URL

使用fsockopen的原始HTTP调用有什么问题?

POST /api/?action=report HTTP/1.1
Host: www.webhosting-performance.com
Content-Type: application/x-www-form-urlencoded
Conent-Length: 9
Connection: close
test=test

远程脚本显示var_dump($_POST)为空。

我的php代码片段如下:

if (ini_get('allow_url_fopen') > 0) {
  $parts = parse_url($url);
  $fp = fsockopen($parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30);
  if (!$fp) throw new Exception("Problem with $url, $errstr");
  $post_string = $post_fields ? http_build_query($post_fields) : '';
  $out = ($post_string ? "POST " : "GET ") . $parts['path'] . ((isset($parts['query'])) ? "?" . $parts['query'] : false) ." HTTP/1.1'r'n"
       . "Host: ". $parts['host'] ."'r'n"
       . ($post_string ? "Content-Type: application/x-www-form-urlencoded'r'n" : false)
       . "Conent-Length: ". strlen($post_string) ."'r'n"
       . "Connection: close'r'n"
       . "'r'n" . $post_string;
  fwrite($fp, $out);
  // ...
} else {
  // use curl
}

您基本上只是有一个拼写错误:

Conent-Length: 9

参见Content-Length: 中缺失的t

真正的问题是(不要诋毁你自己构建东西的努力),你为什么不使用cURL或PEARs HTTP请求类?

为什么不使用PEAR::Http_Request2