0

I am trying to make my website so that you have to log in in order to view some files. I got the login up and running with mySQL databases and everything is working fine, except that i don't want to manually put edit all my 1000+ html files to check if the user is logged in. I have tried using htaccess, but the popup is so ugly i can't stand it.

Now, the question is, can i password-protect a bunch of files on my website without manually modifying all of them, or can i make the "htaccess login form" look good. Thanks.

user2246998
  • 71
  • 2
  • 5
  • I'm assuming you have an open directory that's viewable by going to `yoursite.com/directory`? If so, you can [turn off Directory Indexes](http://stackoverflow.com/questions/2530372/how-do-i-disable-directory-browsing), then use PHP to authenticate the user and output the files in an obtainable format. – Axel Oct 07 '13 at 17:17
  • And how would i go about outputting the files? – user2246998 Oct 07 '13 at 18:17
  • Search for "how do I output files in PHP". There are thousands of articles detailing how to do this. – Axel Oct 07 '13 at 18:33

1 Answers1

2

You could put all of your HTML files in a directory outside of the webroot, then refer to them through URL rewriting or a basic querystring variable passed to a single PHP script.

For example:

<?php
// Get the file from ?whichfile=(...)
$whichfile = $_GET['whichfile'];

// Put your logic here to verify that the user is logged in / has a valid session ID, etc.
// You should also put some checks on the value that is passed through "whichfile"
// to prevent users from accessing things they shouldn't.

// Edit: example to prevent this:
// $whichfile = "../../../../etc/passwd";

$fname = pathinfo($whichfile, PATHINFO_FILENAME);
$ext = pathinfo($whichfile, PATHINFO_EXTENSION);
$fname .= ($ext ? ".".$ext : "");

if (file_exists("/var/www/folder/out/of/webroot/".$fname)) {
   $blob = file_get_contents("/var/www/folder/out/of/webroot/".$fname);
   header("Content-Type: text/html; charset=utf-8");
   print $blob;
}
Will
  • 2,343
  • 1
  • 14
  • 14
  • Be aware when using this answer that this may lead to file system exposure outside the document root, for example when requesting `../../../../../../../etc/passwd` – Ferrybig Oct 24 '17 at 13:43
  • @Ferrybig That was the purpose of the comment "// You should also put some checks on the value that is passed through "whichfile" to prevent users from accessing things they shouldn't." Edited with example. – Will Oct 27 '17 at 21:47