【问题标题】:Hide the real file path to prevent hotlinking隐藏真实文件路径,防止盗链
【发布时间】:2017-03-30 15:19:55
【问题描述】:

我正在使用以下代码隐藏真实文件路径以防止盗链。每当我尝试通过新创建的地址下载文件时,包括文件大小和文件名在内的一切都正常,但是当我尝试打开文件时,无论是 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();

我做错了什么?!

【问题讨论】:

  • 在文本编辑器中检查文件的内容,看看它是否真的如您所愿。
  • @PeeHaa 是的。当我从服务器正常下载文件时,它可以工作。
  • @Martin 没有帮助。我仍然遇到同样的错误。
  • 好的,那么我会冒险您的文件大小不完全正确,因此请尝试注释掉 Content-Length 标头并查看下载是否使用动态大小而不是规定的固定大小.
  • @RyanVincent 我查过了。但是,我不明白两个文件中发生了什么。但是,这是结果:已添加(155)已删除(796)已更改(405)

标签: php


【解决方案1】:

我更改了我的代码并添加了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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多