PHP中受密码保护的目录和文件 [英] Password protected directory and files in PHP

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

问题描述

我正在创建一个简单的私人页面,其中包含一些要下载的文件的链接.我已经用简单的会话管理完成了,但我有一个问题:如果有人点击文件 url,他可以在没有身份验证的情况下下载文件.那么我能做些什么来避免这种情况呢?我可以进行 HTTP 身份验证,但我想要一个自定义登录表单,而不是弹出窗口.

Im creating a simple private page with links to some files to download. I've done it with simple session management but I have a problem: if somebody click on the file-url he can download the file without the authentication. So what I can do to avoid this? I can make a HTTP Authentication but I want a custom login form and not the window popping out.

有什么想法吗?

谢谢

推荐答案

我想现在回答有点晚了.无论如何,它可能会帮助其他人.

I guess it's a little bit late to answer. Anyway, it may help other people.

为了防止文件被直接下载,您必须结合使用 PHP + .htaccess.

To protect files from direct downloads, you have to use a combinaison of PHP + .htaccess.

让我们承认 ./downloads/是您存储要下载的文件的文件夹.首先,您已将 .htaccess 放在此文件夹中.

Let's admit that ./downloads/ is the folder where you store files you want to be downloaded. First, you have put .htaccess in this folder.

deny from all

这将保护每个人的文件夹,除了在服务器端执行的脚本.

This will protect the folder to everybody, except scripts wich are executed on the server side.


这是您可以在根目录下编写的 PHP 脚本示例 ./


Here is an example of a PHP script you can write at the root directory ./

<?php
    if(!empty($_GET["filename"]))
    {
        //Here is the path to the folder containing files to download
        $my_download_folder = "./downloads/";

        //Preparing headers
        header("Content-type: application/force-download"); 
        //You can use more headers :
        //header("Content-Length: ".filesize($my_download_folder . $_GET["filename"]));
        //header("Content-Disposition: attachment; filename=".basename($my_download_folder . $_GET["filename"]));

        //You can check if the file does exist
        //if (!file_exists($my_download_folder . $_GET["filename"])) 
        //exit(); 

        //Reading file will trigger download on the browser side
        readfile($my_download_folder . $_GET["filename"]);
    }
?>

<html>
    <form action="" method="GET">
        <input type="text" name="filename" id="filename" />
        <input type="submit" value="Download It !" />
    </form>
</html>

这个脚本可以直接使用.但小心点.实际上有一个主要的漏洞:使用此表单,您可以下载服务器的任何文件(包括像 config.php 这样的文件,它包含对您的数据库的访问权限).要修复该漏洞,您可以使用 ID:

This script is usable as it is. But be careful. Actually there is a major vulnerability : With this form you can download any file of the server (including a file like config.php which contains access to your database). To fix that vulnerability you can use IDs :

if ($_GET["id"] == 1)
    $filename = "toto.pdf"
if ($_GET["id"] == 2)
    $filename = "fish.png"



它提供了一个很好的例子,可以保护文件不被直接下载,但不能被 PHP 下载.



It provides a good example of protecting files from direct download but not from PHP download.

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

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