2013-04-22 17 views
0

假设我在PHP中有以下脚本来创建目录路径/ Users/abc/bde/fgh中所有文件的列表。现在我想让他们为相同的文件下载链接,我该如何实现?PHP - 在HTML中创建一个下载链接到本地​​文件夹中获取的所有列表项目

$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); 

在此先感谢。

回答

0

你在找什么可能是一种强制下载任何文件类型的权利?

看看这段代码,你可能想要添加更多的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}”。为了安全,请不要包含文件路径。这种方法存在安全问题,但对您而言可能并不重要,这完全取决于您的情况,下载的内容以及是否是公开数据?

+0

没有帮助,当我运行代码时出现错误,表示头文件已存在。 – user2309039 2013-04-24 17:26:22

+0

根本不能有任何输出到浏览器。确保没有错误,万无一失,在你最后一次?>声明等空间。确保你没有从其他地方传递头文件。您也可以搜索“php force file download”以找到类似的解决方案。 – Danny 2013-04-24 17:35:30

相关问题