Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP protect directory from direct URL access

I have an ADMIN script.

admin/index.php

All activity is done through this index.php file.
Users are logging in before gaining access to the program functionality.
$_SESSION['user_authenticated'] is created and set to true.

admin/template/..

This folder contains images, css, javascript files.
They are used only within this ADMIN. (in the backend only)

The question:

I need all the content from admin/template/.. directory to be protected against direct access.
It should be available only to authenticated users.

I guess there has to be a .htaccess redirecting requests to check_session_auth_variable.php, which looks if $_SESSION['user_authenticated'] is true or false and redirects to requested file or throws a 404 error?

I know that the best option would be to place the directory outside of the web root, but in my case I need to keep the directory structure as is, without modification.

like image 249
acoder Avatar asked Oct 30 '25 08:10

acoder


1 Answers

admin/.htaccess:

RewriteCond %{REQUEST_FILENAME} !check_auth.php
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* check_auth.php?file=$0 [QSA,L] # pass everything thru php

admin/check_auth.php:

$file = $_GET['file'];
if($_SESSION['user_authenticated']) {
    // please mind you need to add extra security checks here (see comments below)
    readfile($file); // if it's php include it. you may need to extend this code
}else{
   // bad auth error
}
like image 70
Peter Avatar answered Oct 31 '25 22:10

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!