[英]Problem when posting a file with curl in php
我正在嘗試在php中發布帶有curl的文件,但是該文件從未被服務器上傳/接受。 我已經搜索並嘗試了幾個小時,但是我找不到錯誤所在,其他所有人的示例和代碼似乎都可以用,但不是這樣。
這是代碼:
<?php
$url = "http://jpptst.ams.se/0.52/default.aspx";
$headers = array(
"Content-Type: text/xml; charset=iso-8859-1",
"Accept: text/xml"
);
$data = array("file" => "@documents/xmls/1298634571.xml");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
我得到的結果是:
string(904) "HTTP/1.1 100 Continue
HTTP/1.1 200 OK
Date: Mon, 25 Jul 2011 19:13:41 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 659"
那就是我得到的全部..該文件從未被服務器接受。 如果有人可以幫助我解決這個問題,將不勝感激:)謝謝!
您正在嘗試通過HTTP發布上傳文件,因此發送Content-type: text/xml
標頭是不合適的。 HTTP文件上傳實際上是作為multipart/form-data
,實際上與MIME編碼的電子郵件附件幾乎相同。 PHP的curl將自動為您填充標題詳細信息。 同樣,Accept標頭也不是必需的。
檢查您要上傳的.xml文件的路徑是否正確。 您尚未指定前導/
,因此該路徑是相對於您的PHP腳本執行位置的。
更換:
$data = array("file" => "@documents/xmls/1298634571.xml");
有了這個:
$data = array("file" => "@".realpath('documents/xmls/1298634571.xml'));
試試看,可能會起作用,我不確定。
編輯:
試試看:
<?php
$xmldatafile="documents/xmls/1298634571.xml"; // Make sure the file path is correct
function postData($postFields,$url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST ,1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,$postFileds);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_HEADER ,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER ,1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$xmlData = file_get_contents($xmldatafile);
$postFileds = 'data='.$xmlData;
$result = postData($postFields,"http://jpptst.ams.se/0.52/default.aspx");
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.