【问题标题】:wget return downloaded filenamewget 返回下载的文件名
【发布时间】:2011-01-30 15:59:12
【问题描述】:

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

例如,如果我尝试

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

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

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

我想要这样的东西:

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

【问题讨论】:

    标签: php return wget filenames


    【解决方案1】:

    也许那是某种作弊,但为什么不呢:

    • 自行决定wget 应创建的文件的名称
    • 告诉wget应该下载到那个文件
    • 下载完成后,使用该文件 -- 因为您已经知道名称。

    查看 wget 的 -O 选项;-)


    例如,从命令行运行:

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

    将创建一个名为 my-output-file.html 的文件。

    【讨论】:

    • +1 - 解决问题通常需要问自己是否解决了正确的问题:)
    • 很好的解决方案,但我应该澄清一下 wget 的目标可能是图像或样式表,或任何其他文件。我更新了问题以反映这一点。
    【解决方案2】:

    如果您的要求很简单,比如获取 google.com,那么在 PHP 中完成

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

    【讨论】:

    • 对我来说似乎是最好的答案 - 即根据需要调用文件,而不必获取文件名,并避免从 PHP 执行 shell 脚本。要确定文件是否为 css、html 等,请在 $http_reponse_header 数组中自动填充 Content-Type 字符串。
    【解决方案3】:

    在类似 Linux 的系统上,您可以这样做:

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

    如果./downloads 目录中没有其他进程正在创建文件,则此方法有效。

    【讨论】:

    • 您真的需要调用系统ls 来在PHP 中列出目录吗? :) PHP 自己的readdir()glob() 怎么样
    • 我最终做了类似的事情,但避免了系统调用。为了获取最近更新的文件,我使用了以下代码:code $dir = "./downloads"; $newstamp = 0; $新名称 = ""; $dc = opendir($dir); while ($fn = readdir($dc)) { # 消除当前目录,父目录 if (ereg('^\.{1,2}$',$fn)) continue; $timedat = filemtime("$dir/$fn"); if ($timedat > $newstamp) { $newstamp = $timedat; $新名称 = $fn; } }
    • 代码搞砸了,本来应该是一个答案,所以我也添加了它作为答案。
    【解决方案4】:

    我最终使用 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
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多