In this article, James presents a very simple way to add login/logout security in PHP using session handling.First off, let me say that, yes, I am still a beginner with PHP.
|
In this article, James presents a very simple way to add login/logout security in PHP using session handling.First off, let me say that, yes, I am still a beginner with PHP. Throughout the course of learning PHP though, whenever I’m stuck I like to go online to some of the chat rooms and ask for help. I have found, though, that the reputation of ‘computer geeks’, as parodied on Saturday Night Live, is well deserved by a lot of people. Asking for help from them was like asking them to let you borrow that authentic Klingon uniform they have in the display case down there with them in their parents’ basement (can you feel the love?). While I did find some help (after a lot of persistence), one thing I noticed with myself and with other novices was that the help came in a form as if we were on their level of programming, or we were met with a mass of arrogance and condescension, so, myself, I would still have to spend a couple of hours finding tutorials and articles here at DevArticles.com. But, I still had to have some things explained to me, which was a whole new task in itself. As I’ve grown a little more with my skills in PHP though, I’ve also begun offering help to other beginners with what knowledge I have and can share. One of the biggest problems I always get asked about is how to protect an area with a login and with sessions. I do not claim that this method is the strongest or the most secure, but that it is a simple solution to a beginner’s problem. One of my own preferences as a beginner when writing code is to use an editor, and one that is able to check the syntax as I have written it and return any errors. My own personal preference is one I have found to be a very good and inexpensive one. Ankord’s PHP Expert Editor , is, for me, a decent editor, and it only costs $35 to buy. You can also download a 30 day trial version from their site to try first. (No, I’m not affiliated with the company, I just like the product.) For it to check for syntax errors, you need to download and install the latest version of PHP. This editor is just my own personal preference; you may have your own or prefer not to use one, and I make no claims regarding your own experience with this editor. After trying a few different methods for simple form-based user authentication, I have found this method the least troublesome, especially when I wanted to add more to the authentication, such as simple access logging, but we will not be able to go into that here. This article does assume that you have some basic knowledge of PHP and HTML, but I hope that I have explained it in a way that any beginner can follow. I just wanted to share my knowledge of PHP that I have gained so far with other beginners, and would like to keep sharing it as I continue to progress.
(Page 2 of 5 )
The first thing you will need for this is the MySQL table that will hold the login information. For the scope of this article each record will only hold three pieces of information:
Table: users
| Column Name |
Type |
Null |
Primary Key |
Extra |
| user_id |
int(8) |
No |
PK |
AUTO |
| username |
varchar(11) |
No |
|
|
| password |
varchar(32) |
No |
|
|
Once we have the table created, now we need to populate it with some user information.
INSERT INTO users (username, password) VALUES (‘someUser’, md5(‘somePass’));
The username and password values can be whatever you want tlhem to be. The md5() function is built into PHP, and will convert your password into a 32 character string. This is one good method for encrypting password information. Whenever you use this, though, you should be careful. The conversion is one-way, and you cannot decrypt your password to read it.
Are you asking yourself “Then how am I going to be able to make sure the user is entering the right password?†Don’t worry, all will be revealed.
Now let’s create the login.htm form:
<html> <head> <title>Login</title> </head> <body> <form method="POST" action="login.php"> Username: <input type="text" name="username" size="20"> Password: <input type="password" name="password" size="20"> <input type="submit" value="Submit" name="login> </form> </body> </html>
Let’s look at the code for login.php:
<?PHP //check that the user is calling the page from the login form and not accessing it directly //and redirect back to the login form if necessary if (!isset($username) || !isset($password)) { header( "Location: http://www.yourdomain/login.htm" ); } //check that the form fields are not empty, and redirect back to the login page if they are elseif (empty($username) || empty($password)) { header( "Location: http://www.yourdomain.com/login.htm" ); } else{
//convert the field values to simple variables
//add slashes to the username and md5() the password $user = addslashes($_POST['username']); $pass = md5($_POST['password']);
//set the database connection variables
$dbHost = "localhost"; $dbUser = "yourUsername"; $dbPass = "YourPassword"; $dbDatabase = "yourDB";
//connet to the database
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
$result=mysql_query("select * from users where username='$user' AND password='$pass'", $db);
//check that at least one row was returned
$rowCheck = mysql_num_rows($result); if($rowCheck > 0){ while($row = mysql_fetch_array($result)){
//start the session and register a variable
session_start(); session_register('username');
//successful login code will go here... echo 'Success!';
//we will redirect the user to another page where we will make sure they're logged in header( "Location: checkLogin.php" );
}
} else {
//if nothing is returned by the query, unsuccessful login code goes here...
echo 'Incorrect login name or password. Please try again.'; } } ?>
And that’s it. Good luck.
<new_page>
(Page 3 of 5 )
All right, I’m kidding. We’re going to take a closer look at the code and see what it’s doing. We’ll start with login.php.
<?PHP //check that the user is calling the page from the login form and not accessing it directly //and redirect back to the login form if necessary if (!isset($username) || !isset($password)) { header( "Location: http://www.yourdomain/login.htm" ); } //check that the form fields are not empty, and redirect back to the login page if they are elseif (empty($username) || empty($password)) { header( "Location: http://www.yourdomain.com/login.htm" ); }
This part of the code will check to make sure that the user is actually coming from login.htm, and not accessing the code directly. If they haven’t gotten here by using the login form, it will redirect them back to the page. If they have tried to login, the second part will verify that they didn’t submit any blank fields. If they have, it will send them back to try again.
else{
//convert the field values to simple variables
//add slashes to the username and md5() the password $user = addslashes($_POST['username']); $pass = md5($_POST['password']);
//set the database connection variables
$dbHost = "localhost"; $dbUser = "yourUsername"; $dbPass = "YourPassword"; $dbDatabase = "yourDB";
//connet to the database
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
The $_POST variable is a global PHP variable. The syntax is $_POST[‘input_variable’], where input_variable is the name of the input field on the form, in this case, username and password. This holds the data that was posted from the input fields on the form. The addslashes() function will add slashes to the username string, automatically escaping any quotes in the string. The md5 function, again, will convert the string that the user has entered for the password field into a 32 character string. We convert the input from the form fields to simple variables to make the information easier to work with.
Once we have handled the input from the form, we must now connect to the database using the mysql_connect() function, then select the individual database we will be working with by using the mysql_select_db() function.
$result=mysql_query("select * from users where username='$user' AND password='$pass'", $db);
//check that at least one row was returned
$rowCheck = mysql_num_rows($result); if($rowCheck > 0){ while($row = mysql_fetch_array($result)){
//start the session and register a variable
session_start(); session_register('user');
//successful login code will go here... echo 'Success!';
//we will redirect the user to another page where we will make sure they're logged in header( "Location: checkLogin.php" );
}
} else {
//if nothing is returned by the query, unsuccessful login code goes here...
echo 'Incorrect login name or password. Please try again.'; } } ?>
Now that we’re connected to the database, let’s verify the user. We start by querying the database table users to make sure the username and password information submitted by the user exists. If the information is found and a row returned, from here we will login the user and set the session variable needed for protecting the rest of our area.
To begin, we use session_start(). This is used to start the user’s session based on the current session id being passed by the POST method from login.htm. Once we have the session started, we register a variable that will be passed along as long as the current user’s session is active. In this case we’re using the variable $user, which we assigned the data from $_POST[‘username’]. After we have the session variable registered, we will then redirect the user to our next page, which can only be accessed by a user who is logged in.
The end of the code is in case the user’s name and password cannot be found in the database. In which case they can be redirected to another page, an error message can be displayed, or they can be redirected back to the login page.
(Page 4 of 5 )
Let’s begin by taking a look at our checkLogin.php page:
<?php
//start the session session_start();
//check to make sure the session variable is registered if(session_is_registered('username')){
//the session variable is registered, the user is allowed to see anything that follows
echo 'Welcome, you are still logged in.';
} else{
//the session variable isn't registered, send them back to the login page header( "Location: http://www.yourdomain.com/login.htm" ); }
?>
At the very top, we see the session_start() function. Not only is this used to begin a new session, it is also used to continue an already active one, which is what we’re doing here. Now we will check to make sure that username is registered as it should be for a user to access this page. If it isn’t, then the user isn’t properly logged in, and we want them redirected back to the login page.
Note: If a user has logged in and accessed this page, if we hadn’t included session_start() at the beginning, they would be redirected back to the login page. For any pages you want protected from someone who isn’t authorized, ‘session_start()’ and ‘if(session_is_registered()){…’ should be at the very top of your code. You can make this a little easier by putting it in a separate PHP page and ‘include’ it. Includes are outside the scope of this article, though, so we won’t be going into them here.
Once it is verified that the user is logged in (the session variable is registered), they will be able to continue on with whatever you want them to see from this point.
Wrapping It Up
When the user is done, we want them to log out, so let’s create our logout.php page:
<?php //start the session session_start();
//check to make sure the session variable is registered if(session_is_registered('username')){
//session variable is registered, the user is ready to logout session_unset(); session_destroy(); } else{
//the session variable isn't registered, the user shouldn't even be on this page header( "Location: http://www.yourdomain.com/login.htm" ); } ?>
Again, at the very top, we see session_start() and if(session_is_registered(){… Remember, in order for the user to be able to do anything during their session this needs to be in place, and even though the user is logging out, this still also protects the page from unauthorized access.
Because we’ve registered a session variable, we’re going to get rid of it by using the session_unset() function. This will remove the variable from the session. And to completely close the session, we will use the session_destroy() function. This destroys any data associated with the session.
<new_page>
Simple enough? I hope so, and I hope this has been of some help to anyone who is working with logins and sessions. As I mentioned earlier, this probably isn’t the most secure method of working with sessions and logins to protect an area of your website, so you probably don’t want to use it to protect very sensitive information. However, this is a beginning step for you to gather a little more knowledge and experience about working with sessions and user authentication.
I also hope any other beginners, like myself out there will be able to use this example, and expand on it, or that it has helped them a little more in the expansion of their knowledge and experience with PHP. Next, I hope to expand on this article myself by creating an administration area (a project I’m currently working on), and showing how to handle results of the database, limit them, perform date searches, and update and manipulate the data.
PHP for Beginners by a Beginner: Simple Login, Logout, and Session Handling - Conclusion
PHP for Beginners by a Beginner: Simple Login, Logout, and Session Handling - Moving It Around
PHP for Beginners by a Beginner: Simple Login, Logout, and Session Handling - Breaking It Down
PHP for Beginners by a Beginner: Simple Login, Logout, and Session Handling - Building It Up
|
Tags: PHP Simple Login Logout and Session Handling |
PDF |
Print this article |
Bookmark and share this article:
|
|
Enter comment