我尝试通过PHP cURL创建API,而我的客户端(表单提交)正在从API接收数据。它只是没有发布到API。
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type= application/json"));
curl_setopt($ch, CURLOPT_POST, true);
// execute the request and store the return value.
$message = curl_exec($ch);
echo 'Message returned from API is:' . $message;
这是从API接收消息的代码。它正在返回一条消息,所以希望没有错误。
这是api代码(下面):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>The API</title>
</head>
<body>
<?php
//date, job number, customer, worksite, duties performed, total hours spent, type of hours
$date = $_POST['date'];
$jobnumber = $_POST['jobnumber'];
$customer = $_POST['customer'];
$worksite = $_POST['worksite'];
$duties = $_POST['duties'];
$hours = $_POST['hours'];
$hourtype = $_POST['hourtype'];
$username = $_POST['username'];
$ok = true;
$error ;
//validate the inputs
if (empty($date)) {
$ok = false;
$error .= "Date field empty, ";
}
if (empty($jobnumber)) {
$ok = false;
$error .= "Job Number field empty, ";
}
if (empty($customer)) {
$ok = false;
$error .= "Customer field empty, ";
}
if (empty($worksite)) {
$ok = false;
$error .= "Worksite field empty, ";
}
if (empty($duties)) {
$ok = false;
$error .= "Duties field empty, ";
}
if (empty($hours)) {
$ok = false;
$error .= "Hours field empty, ";
}
if (empty($hourtype)) {
$ok = false;
$error .= "Hour type not specified, ";
}
$data = $date . ', ' . $jobnumber . ', ' . $customer . ', ' . $worksite . ', ' . $duties . ', ' . $hours . ', ' . $hourtype;
echo $data;
?>
</body>
</html>
我的提交页面正在返回&#34;从API返回的消息是:,,,,,,&#34;
我做错了什么?
答案 0 :(得分:0)
您似乎将数组传递给cURL。
$data = array( 'date' => $date, 'jobnumber' => $jobnumber, 'customer' => $customer, 'worksite' => $worksite, 'duties' => $duties, 'hours' => $hours, 'hourtype' => $hourtype, 'username' => $username );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
相反,为cURL构建一个查询字符串,以便像这样工作:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
原因是,如果您传入数组,Content-type
标头会自动设置为multipart/form-data
,但您需要application/x-www-form-urlencoded
,以便您可以通过全局$_POST
访问POSTed信息{1}}。