PHP -在HTML中创建从本地文件夹获取的所有列表项的下载链接


PHP - Creating a download link in HTML to all the list items fetched from a local folder

假设我在PHP中有以下脚本来创建目录路径/Users/abc/bde/fgh中的所有文件列表。现在我想让它们成为相同文件的可下载链接,我该怎么做呢?

$path = "/Users/abc/bde/fgh"; 
// Open the folder 
$dir_handle = @opendir($path) or die("Unable to open $path"); 
// Loop through the files 
while ($file = readdir($dir_handle)) { 
if($file == "." || $file == ".." || $file == "index.php" ) 
    continue; 
    echo "<a href='"$file'">$file</a><br />";   
  } 
// Close        
closedir($dir_handle); 

您正在寻找的可能是强制下载任何文件类型的方法,对吗?

看一下这段代码,你可能想要添加更多的mime类型,这取决于你让人们下载什么类型的文件。

此代码复制自:http://davidwalsh.name/php-force-download

// http://davidwalsh.name/php-force-download
// grab the requested file's name
$file_name = $_GET['file'];
// make sure it's a file before doing anything!
if(is_file($file_name)) {
    /*
        Do any processing you'd like here:
        1.  Increment a counter
        2.  Do something with the DB
        3.  Check user permissions
        4.  Anything you want!
    */
    // required for IE
    if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
    // get the file mime type using the file extension
    switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
        case 'pdf': $mime = 'application/pdf'; break;
        case 'zip': $mime = 'application/zip'; break;
        case 'jpeg':
        case 'jpg': $mime = 'image/jpg'; break;
        default: $mime = 'application/force-download';
    }
    header('Pragma: public');   // required
    header('Expires: 0');       // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: '.filesize($file_name));    // provide file size
    header('Connection: close');
    readfile($file_name);       // push it out
    exit();
}

你只需要创建一个新的php页面(或相同的一个),当他们点击下载链接,它去新的页面(或相同的)与文件名参数"file={filename}"。为安全起见,不要包括文件路径。这种方法存在安全问题,但对您来说可能无关紧要,这取决于您的情况和正在下载的内容以及它是否是公共数据。