如何为我的下载按钮实现逻辑

时间:2010-09-22 19:49:53

标签: php linux download

我想知道如何在PHP中为我的下载按钮实现逻辑。我在Web服务器中有一个文件,并有一个带有下载按钮的页面。我想在用户按下载按钮时开始下载文件。如何实施?感谢

2 个答案:

答案 0 :(得分:3)

以下是如何开始下载而不让用户看到文件的真实路径。使您的链接指向download.php?file = filename,并确保该文件存在于下载文件夹中。然后使用此代码检查文件是否存在并让他们下载它。或者,您可以进行登录检查或其他检查。

<?php
//download.php
$dir = '/path/to/file/'; 
if (isset($_GET['file']) && !is_dir($_GET['file']) && file_exists($dir . $_GET['file'] . '.zip')) 
{ 
    $file = $dir . $_GET['file'] . '.zip'; 
    header('Content-type: application/force-download'); 
    header('Content-Transfer-Encoding: Binary'); 
    header('Content-length: ' . filesize($file)); 
    header('Content-disposition: attachment; filename=' . basename($file)); 
    readfile($file); 
} 
else 
{ 
    echo 'No file selected'; 
} 
?>

此外,您还可以使用.htaccess文件阻止访问包含其中文件的文件夹。如果您愿意,请将以下代码放在文件目录中的.htaccess文件中。

order allow, deny
deny from all

答案 1 :(得分:1)

在两个提供的解决方案(readfile或X-Sendfile头)中,文件可以存储在外部公共服务器目录(通常称为htdocs或www)。

//page.php
<form method="get" action="download.php">
    With button <input type="submit" value="Download file" />
</form>
or
With link <a href="download.php">Download file</a>


<?php // download.php
$file = '/path/to/file.zip';

if (file_exists($file)) {
    // send headers that indicate file download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    // send file (must read comments): http://php.net/manual/en/function.readfile.php
    readfile($file);
    exit;
}

如果您的服务器支持X-Sendfile(mod_xsendfile)标头,则更好的解决方法是:

<?php
header('Content-Disposition: attachment;filename=hello.txt');
header('X-Sendfile: /path/to/file.zip');

http://codeutopia.net/blog/2009/03/06/sending-files-better-apache-mod_xsendfile-and-php/

相关问题