php文件下载可防止URL更改



我正在使用它来下载文件:

<a href="download_init.php?Down=01.zip">download here</a>

download_init.php:

<?php
 $Down=$_GET['Down'];
?>
<html>
  <head>
  <meta http-equiv="refresh" content="0;url=<?php echo $Down; ?>">
 </head>
<body>
 </body>
 </html>

单击无ajax的链接时,是否可以防止浏览器URL更改?

download_init.php?Down=01.zip

在这里检查:http://www.firegrid.co.uk/scripts/download/index.php

单击第一个链接,与其他链接不同,URL不会更改。

添加一个 download属性到锚标记:

<a href="download_init.php?Down=01.zip" download>download here</a>

有关 html下载属性

的更多详细信息

如果要使用header,请参考此链接

您可以使用以下代码中所示的少数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属性的解决方案..

最新更新