php通過加http響應頭強制用戶下載

c6e3 9年前發布 | 2K 次閱讀 PHP

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; } ?></pre>

files.php

<a href="downloadFile.php?file=7383">Download</a>

 本文由用戶 c6e3 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!