【问题标题】:PHP subfolder for each user "type"每个用户“类型”的 PHP 子文件夹
【发布时间】:2021-10-31 15:18:26
【问题描述】:

upload 文件夹中有 3 个子文件夹。我的代码如下所示:

if(isset($_SESSION["u_type"]) && $_SESSION["u_type"] == 3) {
    $files = scandir($path."/3/") //$path is set somewhere above
    //...
}

它工作正常,但您实际上可以添加一个简单的 html 标记,例如 <img src="uploads/2/somathing.png/> ,即使您的“用户类型”设置为 3,您也可以从子目录 2 获取任何文件。

有没有办法预防?

我已经试过了:

我正在使用带有Options- Indexes 的 .htacces,但它只会缩短文件的直接列表。

【问题讨论】:

    标签: php security session directory


    【解决方案1】:

    是的,有一种方法可以做到这一点,它需要 Apache 网络服务器(用于 .htaccess 文件):

    拒绝上传文件夹中的所有内容

    将此添加到.htaccess 中的上传文件夹:

    order deny,allow
    deny from all
    

    创建代理php脚本image.php

    创建一个名为 image.php 的脚本并在其中检查您的会话: (您可能需要根据您的要求更新此脚本,这是一个仅支持 jpeg 的简单示例。

    <?php
    
    session_start();
    
    //check session for permission here!
    
    $userTypeId = 1; //change this to requirements
    
    header('Content-type: image/jpeg');
    echo file_get_contents("uploads/" . $userTypeId . "/" . $_GET['image']);
    

    现在通过访问代理脚本来访问图片

    <img src="image.php?image=yourimage.jpg" />
    

    更新;你可以选择重写image.php?image=x.jpg

    您可以选择用.htaccess 重写此路径,这样就好像没有代理.php 脚本在工作。

    RewriteRule ^/a_chosen_path_name/([^\.]+)\.(png|jpg|gif)$    /image.php?image=$1.$2 [NC,L]
    

    之后你可以使用:

    <img src="a_chosen_path_name/yourimage.jpg" />
    

    【讨论】:

    • 我稍后会尝试,如果它有效,我会接受作为答案。
    • 进展顺利吗?
    • 是的,工作正常。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    相关资源
    最近更新 更多