龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

php通过加http响应头强制用户下载

时间:2014-06-19 15:12来源:网络整理 作者:网络 点击:
分享到:
php通过加http响应头强制用户下载 php中可以通过设置header的content-type,强制用户下载内容,而非直接在浏览器中打开,如下代码实现:** downloadFile.php **```{.php}lt;?php$filename = $_GET[#39;file#

php中可以通过设置header的content-type,强制用户下载内容,而非直接在浏览器中打开,如下代码实现:

downloadFile.php

<?php
$filename = $_GET['file']; //Get the fileid from the URL
// Query the file ID
$query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename));
$sql = mysql_query($query);
if(mysql_num_rows($sql) > 0){
    $row = mysql_fetch_array($sql);
    // Set some headers
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Disposition: attachment; filename=".basename($row['FileName']).";");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($row['FileName']));

    @readfile($row['FileName']);
    exit(0);
}else{
    header("Location: /");
    exit;
}
?>

files.php

<a href="downloadFile.php?file=7383">Download</a>
精彩图集

赞助商链接