假设我在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);
提前致谢。
答案 0 :(得分: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}”转到新页面(或相同)。为安全起见,请不要包含文件路径。这种方法存在安全问题,但对您而言可能无关紧要,一切都取决于您的情况以及下载的内容以及是否为公共数据?