Home > Enterprise >  PHP subfolder for each user "type"
PHP subfolder for each user "type"

Time:11-05

I have 3 subfolders in an upload folder. My code looks like this:

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

Its working fine, but you can actually add a simple html tag, like <img src="uploads/2/somathing.png/> and you can get any file from subdir 2 even if your "user type" is set to 3.

Is there a way to prevent it?

I alredy tried:

I'm using .htacces with Options- Indexes in it, but it only brevents direct listing of the files.

CodePudding user response:

Yes, there is a way of doing this, it requires Apache webserver (for .htaccess files):

Deny from all in uploads folder

Add this to your uploads folder in .htaccess:

order deny,allow
deny from all

Create a proxy php script image.php

Create a script named image.php and check your session in there: (You might need to update this script to your requirements, this is a simple example which only supports 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']);

Now access images by accessing the proxy script

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

Update; you can chose to rewrite the image.php?image=x.jpg

You can chose to rewrite this path with .htaccess so it seems as if there is no proxy .php script at work.

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

After which you can use:

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