2011-12-21 166 views
2

我編寫了下面的PHP函數來下載文件,它按預期工作。 然而,當我嘗試下載此文件:curl_exec成功,但輸出文件爲空

$url = 'http://javadl.sun.com/webapps/download/GetFile/1.7.0_02-b13/windows-i586/jre-7u2-windows-i586-iftw.exe'; 
download($url); 

...沒有內容被寫入文件。我無法弄清楚爲什麼。該文件已創建,對curl_exec的調用返回true,但輸出文件保持爲空。該文件可以在瀏覽器中下載,並且該功能可以成功下載其他文件。只是這個文件(主機?),我有問題。

任何幫助表示讚賞。

function download($url) 
{ 
    $outdir = 'C:/web/www/download/'; 
    // open file for writing in binary mode 
    if (!file_exists($outdir)) { 
     if (!mkdir($outdir)) { 
      echo "Could not create download directory: $outdir.\n"; 
      return false; 
     } 
    } 
    $outfile = $outdir . basename($url); 
    $fp = fopen($outfile, 'wb'); 
    if ($fp == false) { 
     echo "Could not open file: $outfile.\n"; 
     return false; 
    } 
    // create a new cURL resource 
    $ch = curl_init(); 
    // The URL to fetch 
    curl_setopt($ch, CURLOPT_URL, $url); 
    // The file that the transfer should be written to 
    curl_setopt($ch, CURLOPT_FILE, $fp); 
    curl_setopt($ch, CURLOPT_HEADER, false); 
    $header = array(
     'Connection: keep-alive', 
     'User-Agent: Mozilla/5.0', 
    ); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
    // downloading... 
    $downloaded = curl_exec($ch); 
    $error = curl_error($ch); 
    curl_close($ch); 
    fclose($fp); 

    if (!$downloaded) { 
     echo "Download failed: $error\n"; 
     return false; 
    } else { 
     echo "File successfully downloaded\n"; 
     return $outfile; 
    } 
} 
+0

如果您嘗試vardump的$下載變量和/或刪除CURLOPT_FILE,你看到什麼了未來通過對捲曲通常會發生什麼? – DaOgre 2011-12-21 01:06:45

回答

4

該url重定向到另一個。您需要將CURLOPT_FOLLOWLOCATION設置爲1才能工作。

2

嘗試添加;

 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); 
//then after curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true); 

檢查一些樣本:http://www.php.net/manual/en/function.curl-exec.php#84774

+0

不知道這是否適用於所有人,但這對我來說是一個Windows問題。 Mac/Unix同事無法複製它。 – Merijn 2012-12-24 09:53:04