【发布时间】:2017-07-11 17:17:45
【问题描述】:
我正在尝试向 API 发送 POST 请求,并且该请求的一部分我正在添加一个 CSV 文件以根据我提供的电子邮件和号码获取返回令牌。前几行代码使用了我从数据库中检索到的数据,并且生成文件并用文本数据填充它是正确的。问题出在我的 cURL 上。当我在 PostMan 中发出这个请求时,结果非常好,我实际上是使用 PostMan 的 PHP-curl 生成的代码来编写这个请求的。但是,这条线
filename=\"".$filename."\"\r\n
由于某种原因,不会调出之前刚刚正确填充的文件,并且 API 日志说该文件中没有数据。这两个文件都位于同一个目录中,所以我真的对自己做错了什么感到茫然。
$file = fopen($filename, "w");
while ($row2 = mysqli_fetch_array($query2)){
$txt = "$row2[email], $row2[firstname], $row2[lastname],
$row[company], $row2[mobilephone]\n";
echo $txt;
fwrite($file, $txt);
}
$curl = curl_init();
echo $filename."\n";
curl_setopt_array($curl, array(
CURLOPT_URL => "https://example.com",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data;
name=\"token\"\r\n\r\12345\r\n
------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n
Content-Disposition: form-data; name=\"datafile\";
filename=\"".$filename."\"\r\n
Content-Type: text/csv\r\n\r\n\r\n
------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
谁能发现我在这里做错了什么?
注意:出于隐私/安全原因,我用虚拟数据替换了几个字段和字符串
【问题讨论】:
-
您传递字符串而不是数组或 json 的任何原因?
-
在他们的应用程序中成功创建调用后,我只是使用 Postman 生成的 PHP-curl 代码