Skip to main content

PHP - header 下載或開啟檔案設定

  • 使用header隱藏實體路徑

PHP 下載檔案設定

<?php
$file = '路徑';
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();//清除緩存
    flush();
    readfile($file);
    exit;
}
?>

 

PHP 開啟檔案設定

<?php
$content = file_get_contents("檔案路徑");
	header('Content-type: txt');
	echo nl2br($content);
?>

nl2br使html輸出換行