2010-08-28 107 views
0

我試圖用位於遠程服務器上的php下載文件,但沒有運氣。我曾嘗試使用fopen,get_file_contents,但沒有任何工作。php從遠程服務器下載文件,從設置標題的下載url

我傳入一個下載URL,它不是確切的文件位置,它是文件的「下載URL」,然後強制瀏覽器下載。

因此,我認爲這就是爲什麼文件fopen和file_get_contents失敗,有人可以告訴我,我必須做什麼從頭文件下載文件設置爲強制文件下載的URL。

任何幫助非常感謝!

+4

請不要在任何情況下告訴我們「沒有運氣」和「不工作」的意思。它會帶走我們猜測的樂趣! – 2010-08-28 23:05:25

+0

哈哈我喜歡那個:D – 2010-08-28 23:09:53

回答

3

雖然技術上不是重複的,這已被要求在此之前:How to get redirecting url link with php from bit.ly

您的問題是的file_get_contents不遵循重定向。查看解決方案的鏈接答案。

+0

謝謝你,你剛剛救了我可能幾個小時更多的混亂和挫折!現在非常有意義。 – thrice801 2010-08-29 00:09:17

1

儘管你沒有清楚地形成你的問題,我想我知道你的意思。 試試這個功能取自php.net評論

沒有測試它,但它看起來不錯,似乎遵循html標題重定向以及元和JavaScript重定向到文件。

<?php 

/*================================== 
Get url content and response headers (given a url, follows all redirections on it and returned content and response headers of final url) 

@return array[0] content 
     array[1] array of response headers 
==================================*/ 
function get_url($url, $javascript_loop = 0, $timeout = 5) 
{ 
    $url = str_replace("&amp;", "&", urldecode(trim($url))); 

    $cookie = tempnam ("/tmp", "CURLCOOKIE"); 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_ENCODING, ""); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); # required for https urls 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10); 
    $content = curl_exec($ch); 
    $response = curl_getinfo($ch); 
    curl_close ($ch); 

    if ($response['http_code'] == 301 || $response['http_code'] == 302) 
    { 
     ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1"); 

     if ($headers = get_headers($response['url'])) 
     { 
      foreach($headers as $value) 
      { 
       if (substr(strtolower($value), 0, 9) == "location:") 
        return get_url(trim(substr($value, 9, strlen($value)))); 
      } 
     } 
    } 

    if ( (preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value)) && 
      $javascript_loop < 5 
    ) 
    { 
     return get_url($value[1], $javascript_loop+1); 
    } 
    else 
    { 
     return array($content, $response); 
    } 
} 

?>