2013-10-31 26 views
1

我有一個在線目錄中存在的文件名列表。什麼是最好的方式來下載他們?例如,我想獲得以下文件:從以下目錄如何下載目錄中的多個文件?

516d0f278f14d6a2fd2d99d326bed18b.jpg 
b09de91688d13a1c45dda8756dadc8e6.jpg 
366f737007417ea3aaafc5826aefe490.jpg 

http://media.shopatron.com/media/mfg/10079/product_image/

也許是這樣的:

$var = filelist.txt 
for ($i in $var) { 
    wget http://media.shopatron.com/media/mfg/10079/product_image/$i 
} 

任何想法?

+0

可能的重複:http://stackoverflow.com/questions/15436388/download-multiple-images-from-remote-server-with-php-a-lot-of-images 答案似乎適用於此處也是。 – frnhr

回答

0
$list = file_get_contents('path/to/filelist.txt'); 
$files = explode("\n", $list); ## Explode around new-line. 
foreach ($files as $file) { 
    file_put_contents('new_filename.jpg', file_get_contents('http://url/to/file/' . $file)); 
} 

基本上你爆炸名單圍繞新線獲得的每一行,然後file_put_contents文件右後無論你是從讓他們的服務器下載它。

+0

'file_get_contents()'可能不適用於某些(或「許多」)主機,請參閱:http://stackoverflow.com/questions/7794604/file-get-contents-not-working – frnhr

0
$files = file('filelist.txt'); //this will load all lines in the file into an array    
$dest = '/tmp/'; //your destination dir 
$url_base = 'http://media.shopatron.com/media/mfg/10079/product_image/'; 

foreach($files as $f) { 
    file_put_contents($dest.$f, file_get_contents($url_base.$f)); 
} 

不言而喻,但有一點:如果你不確定filelist.txt的內容,你應該清理文件名。

+0

迴應Pat的問題。 。這兩個版本都是[IO界限](http://en.wikipedia.org/wiki/I/O_bound),所以速度不會很大不同。但是,file_get_contents優於wget解決方案,原因如下:1)運行exec會帶來很大的安全風險,並且在某些系統上被禁用,2)某些服務器沒有安裝wget。 – iamdev

+0

我明白了,但根據http://stackoverflow.com/a/7794628/2097294使用'file_get_contents'也有可能在某些服務器上啓用,對吧? – tacudtap

+0

你說得對。安全風險是更大的問題。雖然fopen和exec都存在風險,但通常希望儘量減少允許訪問在您的操作系統上運行任意命令(exec,system,passthru)的命令的使用。出於這個原因,exec通常是php編碼器的最後手段。 – iamdev

0

這是我在等待答案時想出的。

<?php 
$handle = @fopen("inputfile.txt", "r"); 
if ($handle) { 
    while (($buffer = fgets($handle)) !== false) { 
     exec("wget http://media.shopatron.com/media/mfg/10079/product_image/$buffer"); 
     echo "File ($buffer) downloaded!<br>"; 
    } 
    if (!feof($handle)) { 
     echo "Error: unexpected fgets() fail\n"; 
    } 
    fclose($handle); 
} 

我通過修改PHP fgets man page的例子得到了這個。我還設置了max_execution_time = 0(無限制)。

如果有人能證明他們的方法更有效率,我會很樂意將他們的答案標記爲已接受。謝謝大家的答案!

相關問題