PHP/MySQLi Creating a Forum - Part 16 - Log In Requirement
Submitted by Yorkiebar on Sunday, January 26, 2014 - 13:25.
PHP/MySQLi Creating a Forum - Part 15 - Password Change Form
Introduction:
This tutorial will be continuing my series of creating a forum in PHP/MySQLi/HTML. In this part I will be showing you how to add login restrictions to certain pages.
Pre-creation:
First you will need a host for your PHP, either a web host or localhost is fine but you will need PHP and MySQL(i) capabilities.
Also, this will not be covering creating users, or styling the pages. For the purpose of using the logged in users username, we will be using $_SESSION['username']; from my login script, you can find that tutorial on my profile page.
Obviously you will also need to go through all the previous parts of this tutorial series which can all be found on my profile tracking page.
How It Works:
To add a login restriction on to a page, we first need to carry the session over as this is how we check if they are logged in...
Then we want to check if our username variable is set within our session (this gets set when we log in, so if it isn't set, we're not logged in)...
We now have the basic check, but that checks if it is set, we want to check if it is not set so we put an inverter before the conditions...
Finally we want to actually redirect the user to the login page if they are not already logged in. We can also output a simple "redirecting..." string to the screen to notify them. Warning; You can not redirect someone if there is already output on the screen which is why you want to do this as high up the page as possible, and we only output text after the redirection code because it will show as it loads the next page...
- }
- }
So there you go, all you need to do now is copy the above code over to any page just below the session_start(); line to make them be required to be logged in before they can access the page.
I have added the code to the following pages; accountPage.php, threadPage.php and userPage.php
We can also do the opposite for login.php to avoid them logging in to the same account if they are already logged in...
Add new comment
- 33 views