隐藏真实文件路径以防止热链接

时间:2016-11-16 12:13:44

标签: php

我使用以下代码隐藏真实文件路径以防止热链接。每当我尝试通过新创建的地址下载文件时,包括文件大小和文件名在内的所有内容都可以,但是,当我尝试打开文件时,无论是PDF文件还是ZIP文件,都说文件已损坏

当我直接从服务器下载文件时,它可以工作,并且没有任何问题。

$file = 'file.pdf';

$path = $_SERVER['DOCUMENT_ROOT'].'/files/';

$file_Path = $path . $file;

list($file_Basename, $file_Ext) = explode('.', $file);

switch($file_Ext)
{
    case "pdf": $ctype = "application/pdf"; break;
    case "exe": $ctype = "application/octet-stream"; break;
    case "zip": $ctype = "application/zip"; break;
    case "rar": $ctype = "application/rar"; break;
    case "doc": $ctype = "application/vnd.ms-word"; break;
    case "xls": $ctype = "application/vnd.ms-excel"; break;
    case "ppt": $ctype = "application/vnd.ms-powerpoint"; break;
    case "gif": $ctype = "image/gif"; break;
    case "png": $ctype = "image/png"; break;
    default: $ctype = "application/force-download";
}

header('Content-Type:'. $ctype);

header('Content-Length:' . filesize($file_Path));

header('Content-Transfer-Encoding: binary');

header('Content-Disposition: attachment; filename="downloaded.pdf"');

readfile($file_Path);

exit();

enter image description here

enter image description here

我做错了什么?!

1 个答案:

答案 0 :(得分:0)

我更改了代码并添加了ob_clean()flush()以使其正常工作:

header('Content-Type:'. $ctype);

header('Content-Disposition: attachment; filename="'.$file->file_Name.'"');
header('Content-Transfer-Encoding: binary');

header("Content-Length: " . filesize($file_Path));

//This part must be added to your code
if (ob_get_length() > 0 ) {
    ob_clean();
    flush();
}

readfile($file_Path);

exit();