PHP - 列出并打开目录中的文件

时间:2016-06-14 10:13:07

标签: php html

我试图将特定目录的内容列为链接,并希望浏览器打开或下载文件,如果我点击它们,因为它通常会像默认的html文件链接那样,但是如果我点击,链接不起作用。 如果我右键单击并复制链接并粘贴到新选项卡,则会打开该文件。

我的代码:

<?php 
    $dir = 'c:/dir/work';
    $files = scandir($dir);
    $filecount = count($files);
    for ($i=0; $i <= $filecount ; $i++) { 
      if ($files[$i] != '.' && $files[$i] != '..') {
        echo '<p><a href="' . $dir . '/' . $files[$i] . '">' . $dir . '/' . $files[$i] . '</a></p>';

      }
    }
?>

3 个答案:

答案 0 :(得分:0)

您应该为要下载的所有文件提供中央处理脚本。所以你的href将指向脚本而不是像这样的文件:

requests

在此脚本中,您需要发送文件的内容处置标头以进行下载,而不是以内联方式显示,如下所示:

import requests
post_data = { 
   # all the data you want to send 
}
response = requests.post('http://localhost:8090', data=post_data)
print response.text

希望这会有所帮助。

答案 1 :(得分:0)

点击生成的链接时,请查看自动下载文件的建议代码。

<?php 
 $dir = 'c:/dir/work';
 $files = scandir($dir);
 $filecount = count($files);
 for ($i=0; $i <= $filecount ; $i++) { 
   if ($files[$i] != '.' && $files[$i] != '..') {
     echo '<p><a href=?file=' . $dir . $files[$i] . '>' . $dir . '/' . $files[$i] . '</a></p>';

   }
 }
if(isset($_GET['file'])){
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($_GET['file']) . "\""); 
    readfile($_GET['file']); 
 }
?>

答案 2 :(得分:0)

感谢您的回复。我尝试过它们,但对我没用。我想我错过了这个基础知识。 最后我想出了别的东西:

// LIST FILES FROM UPLOADS/SUBDIR BY DAY-ID
function list_files_from_subdir ($subdir, $day_id) {

    $upload = wp_upload_dir ();
    $dir = $upload[basedir] . $subdir;
    $url = $upload[baseurl] . $subdir;
    $files = scandir($dir);
    $filecount = count($files);

    for ($i=0; $i <= $filecount ; $i++) {

      $fileday = substr($files[$i], 0, 8);

      if ($day_id == $fileday) {

        echo '<p><a href="' . $url . $files[$i] . '" target="_blank">' . $files[$i] . '</a></p>';

      }

    }

}