A little while back i wrote a tutorial on how to write a simple PHP Login script powered by a small MySQL database. After receiving many emails on the matter i have decided to write a tutorial on how you can check if a user is logged in and a page that will log them out and take them back to the login page.
Things you need
PHP 4 or 5 enabled server
MYSQL database
Some basic HTML and CSS Knowledge (PHP knowledge isnt required i will tell you how to do it here)
About 5 – 10 minutes
Step 1 – Things to know
Ok so the first important thing to know is that the original script is in need of a bit of editing which will be shown in step 2, we need to create a session on the users browser that our script will be looking for to check a user is logged in. The next thing to know is that in order to logout a user you will need to remove this session, otherwise a user could just keep going back to the secure page without logging in.
Step 2 – Editing the old script
Right then so in the old script we need find the following line.
if(mysql_num_rows($result)=="1")
Under that line where you will have something like
{
header("Location: securepage.php");
}
You will need to edit it to have this new line after the first { symbol and before we redirect the user. This is important if you place this line below the redirect the script will leave before you create the session.
session_register("logged1241");
The name you put between the brackets is very important and you should remember it for later on.
Step 3 – Check if a user is logged in
This is a simple yet effective script that will check the user is logged in. Just place this before the tag on any of the secure pages. Note that the name of the session must be identical to that in step 2, if its not then no one will ever be able to access the page.
<?
session_start();
if(!session_is_registered(logged1241)){
header("location:login.php");
}
?>
The above code basically searched for the session we made when the user logged in and if its not found then it will redirect the user to the login.php page, where they can login. By this being placed above the tags it means that the user will not even get a glimpse of the secure page before they are forced to leave.
Step 4 – Logout script
This part is so simple to do, just create a new page called logout.php and inside the page put nothing but the following code snippet.
<?
session_start();
session_destroy();
{header("Refresh: 3; url='login.php'");}
session_start();
?>
The user will be logged out and will be redirected back to the login.php page, to login again if they want.
Hope you enjoyed the tutorial.




