本文實例講述了PHP安全下載文件的方法。分享給大家供大家參考,具體如下:
<?phpheader('Content-Type:text/html;Charset=utf-8');define('ROOT_PATH', dirname(__FILE__));/** * 下載文件 * @param string $file_path 絕對路徑 */function downFile($file_path) { //判斷文件是否存在 $file_path = iconv('utf-8', 'gb2312', $file_path); //對可能出現的中文名稱進行轉碼 if (!file_exists($file_path)) { exit('文件不存在!'); } $file_name = basename($file_path); //獲取文件名稱 $file_size = filesize($file_path); //獲取文件大小 $fp = fopen($file_path, 'r'); //以只讀的方式打開文件 header("Content-type: application/octet-stream"); header("Accept-Ranges: bytes"); header("Accept-Length: {$file_size}"); header("Content-Disposition: attachment;filename={$file_name}"); $buffer = 1024; $file_count = 0; //判斷文件是否結束 while (!feof($fp) && ($file_size-$file_count>0)) { $file_data = fread($fp, $buffer); $file_count += $buffer; echo $file_data; } fclose($fp); //關閉文件}downFile(ROOT_PATH . '/down/Sunset.jpg');?>
說明:文件名稱可以接受中文名稱。文件格式為 utf-8。