【问题标题】:cURL not actually sending POST datacURL 实际上没有发送 POST 数据
【发布时间】:2014-11-13 13:16:36
【问题描述】:

概述
我有一个脚本,我们称之为one.php,它创建了一个数据库和表。它还包含要发布到另一个脚本two.php 的数据数组,该脚本将对数据进行排序并将其插入到我们新创建的数据库中。

非常感谢您的帮助。

问题
two.php 在脚本的最顶部检查了$_POST[] 数组:

if (empty($_POST))
{
  $response = array('status' => 'fail', 'message' => 'empty post array');
  echo json_encode($response);
  exit;
}

通常,除非 post 数组是 empty(),否则不会触发。但是,当通过cURL 将数据从one.php 发送到two.php 时,我收到上述编码数组作为我的响应,并且我的数据不会进一步向下two.php

我将从以下文件中列出相关代码供您查看:

one.php

$one_array = array('name' => 'John', 'fav_color' => 'red');
$one_url   = 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/two.php';

$response = post_to_url($one_url, $one_array, 'application/json');
echo $response; die;

目前这给了我以下信息:

{"status":"fail","message":"empty post array"}

post_to_url()函数,供参考

function post_to_url($url, $array, $content_type) 
{
  $fields = '';
  foreach($array as $key => $value) 
  { 
    $fields .= $key . '=' . $value . '&'; 
  }

  $fields = rtrim($fields, '&');

  $ch = curl_init();
  $httpheader = array(
    'Content-Type: ' . $content_type,
    'Accept: ' . $content_type
  );

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);

  $result = curl_exec($ch);

  curl_close($ch);

  return $result;
}

两个.php

header("Content-type: application/json");
$response = array(); //this is used to build the responses, like below

if (empty($_POST))
{
  $response['status']  = 'fail';
  $response['message'] = 'empty post array';
  echo json_encode($response);
  exit;
}
elseif (!empty($_POST))
{
  //do super neat stuff
}

【问题讨论】:

  • CURLOPT_POST 应该是真还是假,不是你想发多少东西的计数,真把那行改成curl_setopt($ch, CURLOPT_POST, 1);
  • @iamde_coder,很好,谢谢 - 但这并不能解决问题。旁注:奇怪的是,count($array) 在以前的脚本中对我有用。也许任何 1+ 都返回为true
  • 差不多,是的。在 foreach 循环和 rtrim 之后,您完成的 $fields 字符串是什么样的?
  • 使用上面的示例数组,$fields = 'name=John&fav_color=red'
  • $httpheader 仔细看,这个标识符中有两个词,http和header,但是你没有把它们分开。你应该做$http_header

标签: php post curl


【解决方案1】:

因为您将请求正文内容类型设置为“application/json”,PHP 不会在“two.php”中填充$_POST。因为您要发送 url 编码数据,所以最好只发送 Accept: 标头:

curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);

也就是说,“two.php”实际上并没有使用 Accept: 标头并且 always 输出 JSON;在这种情况下,您完全可以不设置CURLOPT_HTTPHEADER

更新

从数组创建 url 编码数据也可以更简单(也更安全):

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));

【讨论】:

  • 我不确定您是否正确阅读了我的问题。我将从表单提交的数据发布到脚本,然后使用 cURL 将其发布到另一个脚本。
  • @Benjamin 我的答案现在清楚了吗?看来你只是为了接受而接受……否则,如果有什么不清楚的地方,请告诉我。
  • 我去吃点东西,但你在第一句话中强调了这个问题。为了清楚起见,我编辑了你的帖子,以防其他人在未来犯同样的错误。感谢您的帮助!
  • http_build_query() 有帮助。谢谢!
【解决方案2】:

我有一些类似的问题,但就我而言,我添加了

Content-Type: {APPLICATION/TYPE}
Content-Length: {DATA LENGTH}

问题解决了。

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2010-11-08
    • 1970-01-01
    相关资源
    最近更新 更多