简体   繁体   中英

Restrict content access only to Logged In users

I have a folder named cache . It has sub-folders and files. I need to make cache content accessible only when isset($_SESSION["logged"]) .

I have routed all requests to cache folder via index.php by placing the following .htaccess file in cache folder :

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^ index.php [L]
</IfModule>

In index.php following check is written :

<?php session_start();
if (!isset($_SESSION["logged"])) {
    die();
} else {
    header('Location: ' . $_SERVER['REQUEST_URI']);
    die;
}

But I am geting error ::

This web page has a redirect loop

ERR_TOO_MANY_REDIRECTS

Could you please debug where I am wrong.

The reason why you get this error simply is that you explicitly implemented an endless loop. Your header() call redirects back to the same URL originally requested, so the rewriting rule applies again, things start all over again.

Instead you should output the contents of the requested cache file:

<?php 
session_start();
$pathToCachedLocation = '/some/path' . $_SERVER['REQUEST_URI'];
if (isset($_SESSION["logged"]) && file_exists($pathToCacheLocation)) {
    readfile($pathToCacheLocation);
}

You will still have to add some additional validation and error handling to make sure the request targets a file actually inside the physical cache location (see realpath() ) and read permission exists (see is_readable() ). Also some http headers probably make sense sending. The above example is kept simple to demonstrate the approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM