Você está na página 1de 8

LOGIN SYSTEM FOR WEBSITE

Part 1: Introduction
Sometimes its important to restrict access to certain parts of a website, and the best way to regulate this access is through a user login system. This article is going to cover the creation of a very simple login system that will help get you started. This system is by no means 100% secure, so we do not recommend using it in a production environment, however we will examine one of the ways a login can be created and well also look at some of the pitfalls of such a system. Before we begin, lets establish the pseudo code of our script and walk through the general process of a login. First, and most importantly, we need a user account. This will include the users login identification number, a username, password, and any other credentials we may want such as access levels or email addresses. To keep this simple, well stick to user id, username, and password. When a user enters his or her login credentials on your site, we will have to verify the credentials and then establish some means to keep track of a users login status. Remember, whenever someone visits a webpage, that page is always loaded as if its the first time someone has been on the site. We need a way to tell the site who the user is so that the site can make adjustments for the logged in account. There are essentially three different parts to this login system. The first part is the PHP code were going to write that will regulate the user access. Well also need a database to store both the user account information as well as temporary session information that remembers what accounts are logged in. The latter can be setup several ways, including the use of PHP sessions, however for this example were going to store the sessions in a database. The third thing well need is a way for the users computer to identify itself. For this were going to store a cookie on the users computer that will be sent to our website every time the user accesses a new page. Lets begin creating the code. If you want to test this code on a working site, we suggest you create a separate user.php file (or equivalent) that will store all of the user functions. In this example well simply reference all of the different parts necessary. To view the final working code as it should appear on a site, go to http://blog.readysetconnect.com/sample.php.txt.

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


<?php $link = mysql_connect("localhost", "username", "password"); mysql_select_db("database_name", $link); function login($username, $password) { $username = addslashes($username); $password = md5($password); $query = mysql_query("SELECT * FROM user_accounts WHERE username='$username' AND password='$password'"); if(mysql_num_rows($query) == 1) { $info = mysql_fetch_array($query); $userid = $info[userid]; $sessionid = md5($userid . time()); $time = time(); @setcookie ('test_account', $sessionid, $time+3600, '/', ''); mysql_query("DELETE FROM user_sessions WHERE userid='$userid'"); mysql_query("INSERT INTO user_sessions (sessionid,userid,timestamp) VALUES('$sessionid','$userid','$time')"); return $userid; } else { return 0; } } function status() { $sessionid = $_COOKIE[test_account]; $oldtime = time() - 3600; $query = mysql_query("SELECT * FROM user_sessions WHERE sessionid='$sessionid' AND timestamp>$oldtime"); if(mysql_num_rows($query) == 1) { $info = mysql_fetch_array($query); return $info[userid]; } return 0; } function logout() { $sessionid = $_COOKIE[test_account]; @setcookie ("test_account",'', time()-99999, '/', ''); mysql_query("DELETE FROM user_sessions WHERE sessionid='$sessionid'"); } if($_POST[username] !='' || $_POST[password] != '') { $login_status = login($_POST[username], $_POST[password]); } else if($_GET[logout]) { logout(); } $userid = status(); if($userid > 0) { echo "Welcome to our site, user #$userid (<a href='?logout'>Click here to logout</a>)"; } else { if($login_status != '' $login_status == 0) { echo "Invalid username/password combo.<br>"; } ?> <form action="sample.php" method="POST"> <input type=text name=username> <input type=password name=password> <input type=submit value="Log In"> </form> <?php } ?>

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


Part 2: Creating the MySQL database
Before we get to programming, lets setup the databases. You will need to create two different tablesone for user accounts and the other for sessions. Setup the tables as follows: Table name: user_accounts Field 1: userid, int(10), primary key, auto_increment Field 2: username, varchar(10) Field 3: password, varchar(32) Field 1 will store our user id number and will be a primary key for unique user identification. Field 2 is our username with a maximum of 10 characters. The number of characters can be set at whatever youd like. Field 3 is our password field and, for this example, needs to be a minimum of 32 characters. You can use a larger size, however all passwords will be 32 characters in length. Table name: user_sessions Field 1: sessionid, varchar(32), primary key Field 2: userid, int(10) Field 3: timestamp, int(12) Field 1 will store our temporary session id and must be 32 characters as well as a primary key. Field 2 is our user id and its size must be equal to the size you selected in the user_accounts table. Field 3 is our time field. There are several ways to store a time in a database, however we will be storing the Unix timestamp.

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


Part 3: Frontend form and validation
In this example were going to have a simple page that will display username and password text fields if a user is not logged in, and a simple greeting if the user is logged in. The HTML form code for the user/pass login should look something like this: <form action=sample.php method=POST> <input type=text name=username> <input type=password name=password> <input type=submit value=Log In> </form> This HTML will give us a simple form with two fields named username and password. When a user enters the login info and clicks the submit button, the page will reload. Now we need to add in the PHP to retrieve these credentials when the page is loaded. To make sure everything works, add all of the PHP code to the top of the document (as seen in sample.php). To simplify the tutorial were going to give you the code for logging in, logging out, and checking user status in one snippet, however we will not be discussing all of it just yet. Here is the code that will regulate the user activity: <?php if($_POST[username] != || $_POST[password] != ) { $login_status = login($_POST[username], $_POST[password]); } else if($_GET[logout]) { logout(); } $userid = status(); ?> Note: The above code must appear before any output in your document. If there is ANY output prior to this code being executed, you will receive errors when cookies are trying to be set during login. We first check to see if the user is logging in, in which case well call the login function, and well also check to see if theyre logging out, in which case we will log out the current account. Finally we check to see the users status. If the user is logged in the userid will equal the user id. Otherwise it is equal to 0. Now lets look at the functions we call in the above code. The first function well check is the login function. This is the meat of the program that will check user credentials. The code looks like this:

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


<?php function login($username, $password) { $username = addslashes($username); $password = md5($password); $query = mysql_query(SELECT * FROM user_accounts WHERE username=$username AND password=$password); if(mysql_num_rows($query) == 1) { $info = mysql_fetch_array($query); $userid = $info[userid]; $sessionid = md5($userid . time()); $time = time(); @setcookie (test_account, $sessionid, $time+3600, /, ); mysql_query(DELETE FROM user_sessions WHERE userid=$userid); mysql_query(INSERT INTO user_sessions (sessionid,userid,timestamp) VALUES($sessionid,'$userid,'$time)); return $userid; } else { return 0; } } ?> We begin by reading in the username and password. We used addslashes() to help protect against SQL injection attacks. Generally you wouldnt have single quotes in usernames, however if someone tries to break into the system this will help protect you. Next we encrypt the password with MD5. MD5 is a hashing algorithm that will scramble any text and return a 32-character string. Whenever you add a user to the database, make sure the password is saved as a 32-character MD5 string. This will guarantee that anyone who may break into your database will not be able to steal your users passwords. Again while this is not foolproof, it does help protect user data. The idea is that instead of matching two visible passwords, its better to match a scrambled password with the real passwords scrambled counterpart. Since MD5 will always return the same 32-character string for a specific input, we can guarantee that the MD5 hash stored in the database will always match the MD5 hash of the correct password. If you do not wish to encrypt your passwords, simply remove this line from the login function. We then check the database to see if a user exists with the entered username/password combo. If a user does not exist well return the integer 0. This is arbitrary, however the number must remain consistent throughout your program. If the user does exist, well fetch the user id number. We then create a session id (again with md5). Note that were not only encrypting the user id as the session id, but were also concatenating the current timestamp to the user id. This will make it near-impossible for a would-be hacker to guess an active session id. You can use other salts to protect the session id even more.

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


After we have our session id we will want to store it on the users computer. To do this we call the setcookie() function. The first parameter, test_account, is simply the name of the cookie. Again you can set this to be whatever you want, however it must remain consistent throughout your code. The second parameter is our cookie contents, in this case the session id. Its important that we only store non-identifiable information in the cookie. If we were to store something such as the user id or a username, it would be very easy for the would-be hacker to spoof the cookie and gain access to your user accounts. By using a session id, the hacker has to know the id in order to spoof; with our MD5 encryption this becomes difficult and makes it harder for the hacker to exploit your script. The third parameter is the cookie expiration time. $time+3600 is the current time plus 3600 seconds, or one hour in the future. Finally we set the directory the cookie is valid for. Its sufficient to leave this parameter set to /. After we set the cookie we need to clear out the session table. First we will want to wipe any old sessions for our user. We then insert the new session so we have something to match the cookie against whenever the user returns to our site.

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


Part 4: Privatizing your pages
Now lets look at the status function. This function will be called on every page we want to protect. It will check to see if the user has an active cookie, and will match the session id in the cookie to our session table. If there is a match, the user will be logged in. The function looks like this: <?php function status() { $sessionid = $_COOKIE[test_account]; $oldtime = $time() 3600; $query = mysql_query(SELECT * FROM user_sessions WHERE sessionid=$sessionid AND timestamp>$oldtime); if(mysql_num_rows($query) == 1) { $info = mysql_fetch_array($query); return $info[userid]; } return 0; } ?> First well grab the session id thats stored in the cookie test_account. The variable $oldtime is the oldest time the cookie could have been created. In this case thats any time over the previous hour. The 3600 seconds must match the number of seconds in the setcookie function. We then query the session table for a match. If we find one we can pull the userid out of the session table and were logged in. Otherwise we return a 0. Depending on your type of site, you may want to store frequently-used information in the session table for easy access. In this case, should we want to pull down the users username, we could use the userid pulled from the session table and then query the user_accounts table and match the user id for the account in question.

www.akshaybaweja.co.cc

www.baweja.co.cc

LOGIN SYSTEM FOR WEBSITE


Part 5: Logout functions
Our final function is the logout function that will wipe our session. That function is simpler and looks like this: <?php function logout() { $sessionid =$_COOKIE[test_account]; @setcookie (test_account,,time()-99999, /, ); mysql_query(DELETE FROM user_sessions WHERE sessionid=$sessionid); } ?> We first grab any session id out of the users submitted cookie. We then delete the cookie on the users computer by setting the cookie expiration date to sometime in the past (effectively deleting it), and we finally delete the session record from our database. Before we can finish off the program we have two more tasks. The first is to throw an error message if the user enters invalid login credentials, and the second is to print out a greeting to the user if theyre logged in. Replace the HTML code from before with the following:

<?php if($userid > 0) { echo Welcome to our site, user #$userid (<a href=?logout>Click here to logout</a>); } else { if($login_status != && $login_status == 0) { echo Invalid username/password combo.<br>; } ?> <form action=sample.php method=POST> <input type=text name=username> <input type=password name=password> <input type=submit value=Log In> </form> <?php } ?>
We first to check to see if our status function call returned a user id. If it did we can print out a welcome to the user, giving them his or her user id. We also provide a link for logging out; simply call the same page with logout specified as a URL GET variable to log out. If we dont have a user id, well print out the login form. We also check the login_status variable to see if there was an error. If there was well print this out to the user. This tutorial covers the basic concepts of a user login system, however it certainly doesnt cover everything. There are many websites on the internet that can assist you with the specifics of setting up a database table, basic programming concepts, and anything in between. The full sample program can be found here. Note: In our example we assume you already have a connection to the database established, however sample.php includes the basic MySQL database connection functions.

www.akshaybaweja.co.cc

www.baweja.co.cc

Você também pode gostar