0

What's the best way to 'lock' out non logged in users on a PHP-MySQL website please? Currently I have lock.php includes on all the webpages that will redirect to login if not already logged in. But I realised today that this won't stop people going directly to resources like images..So I supposed that the best thing to do is to redirect everything except the login page with a rewrite rule in the htaccess. Is this common practice? Regs.

1 Answers1

0

If you want to protect everything inside a directory, HTML, images, CSS, JS, etc then using a .htaccess file is the best way to go.

Create a file called .htaccess and put this inside:

AuthType Basic
AuthName "restricted area"
AuthUserFile /full/path/to/.htpasswd
require valid-user

It's important that you specify the full server path to your .htpasswd file - this is a path and not a URL

You then need to create the .htpasswd file with the usernames and corresponding passwords, the format is:

username:password

BUT the password is encrypted. I would recommend using a tool like http://www.htaccesstools.com/htpasswd-generator/ to generate the .htpasswd file.

With this in place then you will need to be logged in before being able to access any files on your site.

Chris
  • 4,672
  • 13
  • 52
  • 93
  • Hi Chris - thanks for your clear response. Is there a way to incorporate my current users stored in the database? Regs. –  Aug 21 '17 at 14:53
  • e.g. only a logged in user can access mysite.whatever/important-page.php but anyone can access mysite.whatever/directory/image.jpg –  Aug 21 '17 at 14:55
  • ideally users wouldn't have to login in one time on the php login page and a second time via htaccess to access the non-public resource files –  Aug 21 '17 at 14:57
  • OK, if you want to protect your images then you can look up about htaccess hotlinking. https://stackoverflow.com/questions/1245869/allow-deny-image-hotlinking-with-htaccess might help. You can then keep your current PHP authentication system – Chris Aug 21 '17 at 15:14