您可以用屈指可数执行实际的下载header
功能如下面的代码所示。
但是;首先,您可能需要在应用程序的根目录下创建一个任意处理文件(例如:download_init.php
)。现在download_init.php
文件里面,你可以添加这样的事情:
<?php
// CHECK THAT THE `d` PARAMETER IS SET IN THE GET SUPER-GLOBAL:
// THIS PARAMETER HOLDS THE PATH TO THE DOWNLOAD-FILE...
// IF IT IS SET, PROCESS THE DOWNLOAD AND EXIT...
if(isset($_GET['d']) && $_GET['d']){
processDownload($_GET['d']);
exit;
}
function processDownload($pathToDownloadFile, $newName=null) {
$type = pathinfo($pathToDownloadFile,
PATHINFO_EXTENSION);
if($pathToDownloadFile){
if(file_exists($pathToDownloadFile)){
$size = @filesize($pathToDownloadFile);
$newName = ($newName) ? $newName . ".{$type}" :basename($pathToDownloadFile);
header('Content-Description: File Transfer');
header('Content-Type: ' . mime_content_type ($pathToDownloadFile));
header('Content-Disposition: attachment; filename=' . $newName);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
return(readfile($pathToDownloadFile));
}
}
return FALSE;
}
然而,这意味着你的链接现在会略有不同href
值,就像这样:
<!-- THIS WOULD TRIGGER THE DOWNLOAD ONCE CLICKED -->
<a href="download_init.php?d=path_to_01.zip">download here</a>
如果你觉得这个标题的方法对于你的目的来说太无关紧要; @Sanchit Gupta提供了一个HTML5 download
属性的解决方案....
提供'download'属性来锚定 –
我认为您可以使用header()函数在download_init中下载文件。 – lalithkumar
这根本不安全;使用标题并将该文件隐藏在根外部以获得更好的安全性。 –