【发布时间】: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