PHP 保护 PDF 和 DOC [英] PHP to protect PDF and DOC

查看:23
本文介绍了PHP 保护 PDF 和 DOC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向网站上的授权用户提供 .pdf.doc 文件.用户只能在登录时看到文件选择页面,但这并不能阻止未经授权的用户在知道完整 URL 的情况下查看文档.

I am trying to provide .pdf and .doc files to authorized users on a website. The user can only see the file selection page when logged in but this doesn't prevent an unauthorized user from viewing the documents if they have knowledge of the full URL.

如何防止未经授权的用户访问这些文件?

How can I prevent unauthorized users from accessing these files?

推荐答案

答案很简单,@Jonnix 在我打字时发布了这个,但我会为你解释更多

the answer is quite simple, @Jonnix has posted this as I was typing but I will explain a little more for you

如果您无法执行此操作,请将您的文件放在公共 HTML 目录之外,请查看@Andri 的替代答案

one put your files outside of your public HTML directory if your unable to do this look at @Andri answer for an alternative

E.G 控制面板设置

user/public_html
    /public_html/download.php

user/documents/
    /documents/file.doc
    /documents/file.pdf

@dhh 已经发布了一个基本的 download.php php 文件,但是当你想强制下载他们的东西时,你可以像在这里找到并提供正确的 mime 类型是他代码的扩展1 强制下载文件,2 允许不同文件类型的最佳方法

@dhh has posted a basic download.php php file however as your wanting to force download their things you can do like finding and supplying the correct mime type here is an extension on to his code as to the best way to 1 force download of a file, and 2 allow different file types

download.php

//check users is loged in and valid for download if not redirect them out
// YOU NEED TO ADD CODE HERE FOR THAT CHECK
// array of support file types for download script and there mimetype
$mimeTypes = array(
    'doc' => 'application/msword',
    'pdf' => 'application/pdf',
);
// set the file here (best of using a $_GET[])
$file = "../documents/file.doc";

// gets the extension of the file to be loaded for searching array above
$ext = explode('.', $file);
$ext = end($ext);

// gets the file name to send to the browser to force download of file
$fileName = explode("/", $file);
$fileName = end($fileName);

// opens the file for reading and sends headers to browser
$fp = fopen($file,"r") ;
header("Content-Type: ".$mimeTypes[$ext]);
// this header tells the browser this is a download and not to try and render if it is able to E.G images
header('Content-Disposition: attachment; filename="'.$fileName.'"');

// reads file and send the raw code to browser     
while (! feof($fp)) {
    $buff = fread($fp,4096);
    echo $buff;
}
// closes file after whe have finished reading it
fclose($fp);

P.S 如果你想添加对其他文件的支持,这里有一个很大的 mime 类型列表https://www.freeformatter.com/mime-types-list.html

P.S here is a big list of mime types if you want to add support for other files https://www.freeformatter.com/mime-types-list.html

这篇关于PHP 保护 PDF 和 DOC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆