0

I want to build a website with protected data in a folder. I have in my PHP a session check for only show the data when logged in.

The data is a couple .PDF and .JPG files.

But when a nog logged-in user the complete url searches he can find and open the files. Example: www.domain.com/protected-data/file.pdf

How do I protect this?

I already did some tricks with the .htaccess.

Order Allow,Deny
Allow from all
<Files ~ "\.(gif|jpg|png|pdf)$">
Deny from all
</Files>

But this script is denying all my files even when a user is logged in.

Jessie
  • 31
  • 1
  • 1
  • 3
  • `allow` and `deny` commands are for allowing or denying requests from particular IP addresses. Your script is working as expected denying access to files since you have written `Deny from all`. Best way to handle this is to redirect all requests to `index.php`, check user's session and forward the request to the requested resource. – nice_dev Mar 27 '19 at 08:57
  • 2
    What you configure in the .htaccess has no idea of your PHP session. You need to handle this _in PHP_ (at least partially) to begin with. Rewrite _all_ requests for the files in question to a PHP script, that checks if the user has access, and if so, reads the file data and passes it on to the client. – 04FS Mar 27 '19 at 08:58

1 Answers1

0

The idea is to have your files in a directory that is not available from outside. Let's say you have the following directory structure:

|_src
     \_.htaccess  
|_private  
     \_.htaccess  
|_public  
     \_read.php  

src/: Contains your classes, the source code.
private/: Contains your JPG and PDF files.
public/: Contains your front controller, the only directy available from the Internet.

src/.htaccess

# No one should be able to access your source code from Internet
Deny from All

private/.htaccess

# No one should be able to access your private files from Internet
Deny from All

Doing so only the public/ directory is reachable from the Internet. In your public/ directory you may have a PHP file that read these files. Here is a little example.

public/read.php

<?php
session_start();
//if the user is logged, read the file and echo it
if (1 === $_SESSION['logged']) {
    //Filename to read could be given like ?file=invoice.pdf
    $file = $_GET['file'];
    //Warning: you should sanitize the $file to prevent an attacker to give a file like "../src/yourclass.php".
    echo file_get_contents(__DIR__.'/../private/'$file);
}

See the Apache documentation about Deny.

Anthony
  • 2,014
  • 2
  • 19
  • 29