cURL实际上并没有发送POST数据

9 php post curl

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

非常感谢您的帮助.

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

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

通常,除非post数组是,否则不会触发empty().但是,当发送数据one.phptwo.phpvia时cURL,我收到上面编码的数组作为我的响应,我的数据不会进一步下降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;
Run Code Online (Sandbox Code Playgroud)

目前这给我以下内容:

{"status":"fail","message":"empty post array"}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

two.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
}
Run Code Online (Sandbox Code Playgroud)

Ja͢*_*͢ck 6

因为您将请求正文内容类型设置为"application/json",所以PHP不会填充$_POST"two.php".因为您要发送url编码数据,所以最好的办法是只发送Accept:标题:

curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
Run Code Online (Sandbox Code Playgroud)

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

更新

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

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
Run Code Online (Sandbox Code Playgroud)