2013-10-31 24 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(无限制)。

如果有人能证明他们的方法更有效率,我会很乐意将他们的答案标记为已接受。谢谢大家的答案!

相关问题