How to create a simple "Members Only" (logged in) site with PHP

I saw a request for a guide on setting up a Members Only site with PHP – where the user logs in and is redirected to a Members Only page. If anyone tries to access the Members Only page while not being logged in, they get redirected back to the login page. I don’t know if this would qualify for a “Community Guide” post because it’s not really specific to Infinity Free. This would work on any server that can run PHP. There are no databases involved in this example, but you could modify the login.php script to check a database full of usernames and passwords instead of hardcoding them into the PHP file.

My simple example has 5 files:

  • index.html - the main login form where the user first starts
  • login.php - a PHP script which contains the usernames & passwords
  • member.php - a PHP script which can only be seen by logged-in members
  • logout.php - a PHP script which logs the user out and redirects them back the login form
  • member.png - a graphic which appears on the member page

You can download all of the files here: https://d0.000.pe/php-member.zip

The files contain lots of comments which explain what each part of the code is doing.

You can see a demo of the site here: https://d0.000.pe/

Username: test
Password: test

If you open the login.php script you can change the usernames and passwords.

The way that the demo works:

  1. The user goes to index.html and types a username and password
  2. The action for the login form sends the data to login.php
  3. The login.php script checks to see if the username/password is valid
  4. If the login is not valid, it shows an error message
  5. If the login is valid, it sets a cookie (valid for 30 days) and redirects them to member.php
  6. The member.php script checks for the “ValidUser” cookie when it loads
  7. If there is no valid cookie, it redirects them back to the index.html page to log in again
  8. If the cookie is there and is valid, it shows them the Members Only page
  9. If the user clicks the Log Out button it redirects them to logout.php
  10. The logout.php script deletes the cookie and redirects them back to the index.html page

The login.php script also checks to make sure that POST data was received. If there is no POST data from the form (example: the user tries to access the page directly without going through the login form) it will give an error and a link back to the login page.

Hopefully, this may be helpful to someone.

2 Likes

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.