How to create Simple "members only" pages using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to create Simple "members only" pages using PHP

Post by Tony » Sun Nov 29, 2009 4:58 am

By combining some of the Tips & Scripts on this page it is possible to make a simple "members only" section on your website. When a user logs in they are automatically sent to their page, and can not get to anyone else's page.

Use the "setting up password protection" tip to set up a password protected directory. Let's call that directory members. Under that members directory have a subdirectory for each member. For example members/joe and members/jane.

Then in that password protected directory members, use the "Passing user authentication information to PHP" to identify the user and route them to the directory with their name. So you have a page members/index.php which would contain a script something like this:

Code: Select all

<?php
$directory = $_SERVER['REMOTE_USER'];  // directory name is the user name
if (file_exists($directory)) {
  header('Location: '.$directory.'/');   // go to the user directory
} else {
  header('Location: http://yourdomain/error.htm');  // not found
}
?>
Then you need to secure each individual members subdirectory so no authenticated member can get to another member's subdirectory. You can do this with another .htaccess file which you put in each member's subdirectory. But there is no need for another identity verification. Simply put these three lines in a .htaccess file in each member's subdirectory (this example being for joe):

Code: Select all

RewriteEngine On
RewriteCond %{REMOTE_USER} !^joe
RewriteRule . http://yourdomain.com/error.htm [L] 
In this example, if anyone other than joe tries to access anything in that subdirectory they will get the error page.

In summary:
  1. A member always goes to page domain.com/members. If the member is not logged in they will get the login prompt and then be sent to their page. If the member has already logged in, they will just be sent to their page.
  2. Using this method you must put each member name in the htpasswd file for authentication, use that name as a directory name, and put that name in the htaccess file for that directory. So it is not maintenance free - but it is very secure, easy and "light weight". Note that all this is case sensitive, Joe is not the same as joe. The .htpasswd member name must match the dirctory name which must match the name used in the .htaccess for that directory.
Post Reply

Return to “PHP & MySQL”