2011-01-31 226 views
5

當我使用linux並嘗試使用此腳本將文件上傳到遠程服務器時,一切正常。但是,如果我使用Windows,那麼腳本不工作。 腳本:cURL將文件上傳到MS Windows上的遠程服務器

$url="http://site.com/upload.php"; 
$post=array('image'=>'@'.getcwd().'images/image.jpg'); 
$this->ch=curl_init(); 
curl_setopt($this->ch, CURLOPT_URL, $url); 
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($this->ch, CURLOPT_TIMEOUT, 30); 
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0); 
curl_setopt($this->ch, CURLOPT_POST, 1); 
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post); 
$body = curl_exec($this->ch); 
echo $body; // << on Windows empty result 

我在做什麼錯?

PHP 5.3

的Windows 7 - 不工作,Ubuntu Linux操作系統的10.10 - 如果你使用的是Windows工作

+0

你有沒有在你的PHP安裝編譯捲曲在你的Windows服務器上?顯示給出的錯誤信息。您可以通過[phpinfo()](http://php.net/manual/en/function.phpinfo.php)腳本檢查安裝。 – Orbling 2011-01-31 00:40:58

+0

錯誤未顯示。 (error_reporting = on) – Dador 2011-01-31 00:46:41

+0

getcwd()不會以斜線結尾返回,所以我錯過了那個,除此之外不應該在Windows上使用反斜槓而不使用反斜槓? – 2011-01-31 00:48:02

回答

4

,你的文件路徑分隔符會\不是Linux的風格/。嘗試

一個明顯的一點是

$post=array('image'=>'@'.getcwd().'images\image.jpg'); 

,看看是否有效。

如果你想使你的腳本方便攜帶,因此它完全可以在與Windows或Linux,你可以使用PHP's predefined constantDIRECTORY_SEPARATOR

$post=array('image'=>'@'.getcwd().'images' . DIRECTORY_SEPARATOR .'image.jpg'); 
4

從理論上講,你的代碼應該是不行的(我的意思是上傳)在任何,UNIX或窗戶。從你的代碼考慮此部分:

'image'=>'@'.getcwd().'images/image.jpg' 

getcwd()返回F:\Work\temp
在Linux中的窗口,它返回/root/work/temp

所以,你上面的代碼可以編譯如下圖所示:

的Windows:'image'=>'@F:\Work\tempimages/image.jpg'
的Linux :'image'=>'@/root/work/tempimages/image.jpg'

由於您提到它在linux中適用於您,這意味着/root/work/tempimages/image.jpg以某種方式存在於您的文件系統中。

我的PHP版本:
的Linux:PHP 5.1.6
的Windows:PHP 5.3.2

1

你應該嘗試var_dump($body)看到什麼$body的確不包含。通過配置cURL的方式,$body將包含服務器的響應或失敗時的錯誤。沒有辦法區分echo的空響應或虛假。這可能是請求正在通過,服務器只是沒有返回。

然而,正如其他人所說,你的文件路徑似乎無效。 getcwd()不輸出最後的/,您需要添加一個才能使代碼正常工作。既然你說過它可以在linux上運行,即使沒有缺少斜槓,我想知道它是如何找到你的文件的。

我建議你創建一個相對於正在運行的PHP腳本的文件路徑,或者提供一個絕對路徑,而不要依賴getcwd()這可能不會返回你所期望的。getcwd()的值在整個系統中可能無法預測,並且不便於攜帶。

例如,如果你想POST文件駐留在同一文件夾作爲你的PHP腳本:

$post = array('image' => '@image.jpg');就足夠了。如果與工作使用PHP's Predefined ConstantDIRECTORY_SEPARATOR

$url = "http://yoursite.com/upload.php"; 
// images\image.jpg on Windows images/image.jpg on Linux 
$post = array('image' => '@images'.DIRECTORY_SEPARATOR.'image.jpg'); 
$this->ch = curl_init(); 
curl_setopt($this->ch, CURLOPT_URL, $url); 
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($this->ch, CURLOPT_TIMEOUT, 30); 
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0); 
curl_setopt($this->ch, CURLOPT_POST, 1); 
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post); 
$body = curl_exec($this->ch); 
var_dump($body); 

getcwd()cURL

1

$post = array('image' => '@/home/youruser/yourdomain/image.jpg');

至於特倫斯說,如果你需要你的代碼跨Linux &的Windows是便攜式的,可以考慮:如果需要,提供絕對路徑xampp 確保在php.ini配置文件中

行號碼952是取消註釋 即 如果行是

;extension=php_curl.dll 

然後使它

extension=php_curl.dll 
1

我認爲,更好的辦法是:

$imgpath = implode(DIRECTORY_SEPARATOR, array(getcwd(), 'images', 'image.jpg')); 
$post = array('image'=>'@'.$imgpath); 
相關問題