tsukimi tsukimi - 7 months ago 16
PHP Question

limit subdirectories to logged in users

How can i do the below probably .htaccess ?

/sp/sitea => /check.php?page=sitea #no trailing forward slash
/sp/sitea/ => /check.php?page=sitea #trailing forward slash
/sp/sitea/index.php => /check.php?page=sitea/index.php #includes a file
/sp/siteb => /check.php?page=siteb

/sp/index.php , /sp/login.php => no redirect


I then want to check the DB using PHP for sitea to see if the user is logged in and then redirect to /sp/sitea If they are not logged in for that site redirect to /login.php

I tried .htaccess below , in sp folder, but doesnt redirect, im not really .htaccess master

RewriteEngine On
RewriteCond %{REQUEST_URI} /
RewriteRule ^\/(.*)$ sp/check.php?path=$1 [L]

Answer

I solved this with a modified .htaccess file

RewriteEngine on
RewriteOptions MaxRedirects=2
RewriteBase /

#dont check non pages
RewriteCond %{REQUEST_URI} !\.(gif|jpe?g|png|css|js)$ 
RewriteRule ^(.*)/(.*)$ /sp/check.php?path=$1&path2=$2 [L,P] #P keeps address in bar after redirect

check.php

<?php
//htaccess redirects here for sitepreview subdomains, then do authentication check and output the html
//cant redirect to page or get redirect loop
session_start();
$dir =  $_GET["path"];
$dir2 =  $_GET["path2"];
//echo $dir;

if(!isset($_SESSION['login_user'])){
    header("Location: /sp/index.php",true,301);
    exit();
}else {
    $name = $_SESSION['login_user']["name"];
    if($name == $dir) {
        $homepage = file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/sp/$dir/" .  (isset($dir2) && strpos($dir2, ".htm") ? $dir2 : "index.html") );
        echo $homepage;
    }
    else {
        header("Location: /sp/index.php",true,301);
        exit();
    }
    exit();
}