简体   繁体   中英

Apache directory listing and prevent users from accessing files without login to PHP form

So this question has been asked but in the other questions the users want to prevent apache from listing a directory. Basically I have a website that has a login to a file exchange system, if the user is logged in then he can get access to content that is uploaded by other users. Here is how I prevent users from accessing certain parts of my site

function loggedin()
{
 if (isset($_SESSION['myusername']) || isset($_COOKIE['myusername']))
 {
        return true;
 }
else {
            return false;
     }
}

I use this code to show all directories in my uploads folder:

<?php
$dir = "./uploads";
$list = scandir($dir); /* This function sorts dirs */
$list = array_diff($list,array(".","..","index.php"));

echo "<ol>";
foreach ($list as $file)
{
   if (!is_dir($file)) echo "<li><a href='https://rye-high.ca/Rye High/$dir/$file'>$file</a></li>\n";
}
echo "</ol>";
?>

NOW for sheer simplicity I allow apache to list the directories using Options Indexes FollowSymLinks because I like how apache does it automatically and prevents me from coding something that might break in php.

My Question: Users that know the filename/folder name can access the files (and directory) directly without logging into the system (ie mysite.ca/Rye High/uploads/ACC 100/. I would like to prevent this by still keeping Option Indexes turned on so that apache can list the files to users who are actually logged in.

How can it be done? .htaccess file?

I considered editing the default apache template code for listing directories however I may not want this for other virtual hosts (globally) in the future.

You can use apache's Basic Auth module ( http://linuxzoo.net/page/tut_authapache.html ) and further you can generate .htpasswd files using PHP - http://www.htaccesstools.com/articles/create-password-for-htpasswd-file-using-php/ .

A good way is to use something like php file manager:

Or you could set a cookie after the user successfully signs in, and then check the cookie in a htaccess: https://stackoverflow.com/questions/19382160/htaccess-compare-cookie-value-and-redirect-if-evaluation-returns-true-false . The issue with this, is that somebody who knows the cookie value will be able to browse your files without signing in in the first place.

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