2010-03-23 198 views
3

我在一个php脚本中使用wget,需要获取下载的文件的名称。wget返回下载的文件名

例如,如果我尝试

<?php 
    system('/usr/bin/wget -q --directory-prefix="./downloads/" http://www.google.com/'); 
?> 

我会得到一个名为index.html在下载目录中的文件。

编辑:页面不会总是谷歌,但目标可能是图像或样式表,所以我需要找出被下载的文件的名称。

我想有这样的事情:

<?php 
    //Does not work: 
    $filename = system('/usr/bin/wget -q --directory-prefix="./downloads/" http://www.google.com/'); 
    //$filename should contain "index.html" 
?> 

回答

0

我结束了使用PHP中使用下面的代码在目录中查找最近更新的文件:

<?php 
system('/usr/bin/wget -q --directory-prefix="./downloads/" http://www.google.com/'); 
$dir = "./downloads"; 

$newstamp = 0; 
$newname = ""; 
$dc = opendir($dir); 
while ($fn = readdir($dc)) { 
    # Eliminate current directory, parent directory 
    if (ereg('^\.{1,2}$',$fn)) continue; 
    $timedat = filemtime("$dir/$fn"); 
    if ($timedat > $newstamp) { 
    $newstamp = $timedat; 
    $newname = $fn; 
    } 
} 
// $newname contains the name of the most recently updated file 
// $newstamp contains the time of the update to $newname 
?> 
3

也许这就是某种作弊,但为什么不:

  • 决定自己名字的文件是wget应创建
  • 指示wget应下载该文件
  • 下载完成后,使用该文件 - 因为您已经知道该名称。

退房wget的;-)


例如,在命令行中运行这个的-O选项:

wget 'http://www.google.com/' -O my-output-file.html 

将创建一个名为my-output-file.html

+0

+1 - 往往解决问题需要问自己,如果你要解决真正的问题:) – 2010-03-23 05:43:47

+0

好解决方案,但我应该澄清,wget的目标可能是图像或样式表或任何其他文件。我更新了这个问题来反映这一点。 – Matthew 2010-03-23 21:12:05

1

,如果你的要求是简单的像刚开google.com,然后做它在PHP中

$data=file_get_contents('http://www.google.com/'); 
file_put_contents($data,"./downloads/output.html"); 
+0

看起来对我来说是最好的答案 - 即调用文件,而不必获取文件名,并避免从PHP执行shell脚本。要确定文件是否为css,html等,需要在$ http_reponse_header数组中自动填充Content-Type字符串。 – fred2 2012-03-10 20:28:42

0

在Linux类系统中,你可以这样做:

system('/usr/bin/wget -q --directory-prefix="./downloads/" http://www.google.com/'); 
$filename = system('ls -tr ./downloads'); // $filename is now index.html 

这个工作,如果没有其他的过程中创造文件在./downloads目录中。

+1

你真的需要调用系统'ls'来完成PHP中的目录列表吗? :)如何PHP自己的'readdir()'或'glob()' – ghostdog74 2010-03-23 05:54:13

+0

我最终做了类似的事情,但避免了系统调用。要获得最近更新的文件,我使用了以下代码: 'code' $ dir =“。/下载“; $ newstamp = 0; $ NEWNAME = ”“; $ DC =执行opendir($ DIR); 而($ FN = READDIR($ DC)){ #消除当前目录,父目录 如果(ereg('^ \。{1,2} $',$ fn))继续; $ timedat = filemtime(“$ dir/$ fn”); if($ timedat> $ newstamp){ $ newstamp = $ timedat; $ newname = $ fn; } } – Matthew 2011-05-06 15:12:24

+0

代码出来搞砸了,本来应该是个答案,所以我也加了一个答案。 – Matthew 2011-05-06 15:27:49