Free PHP code of login script using sessions - Secure and easy

PHP login script is the thing about which you find lots of people searching it. Specially the people who are new to the PHP language it is very important for them to learn user authentication stuff. So I am gonna take this initiative to post a secure php login script and explain it.
For your information we will be using sessions for login. I will mostly emphasize on PHP coding but will give specifications about the html login form. So first things first, make a login form with two fields and one login button. First field must be named "username" and second must be named "password". Post form using method="POST" and action must be another page lets say called doLogin.php which will actually contain the login PHP code.


Now before going further into the PHP lets see out MySQL tables' details which we will be using for login purpose. We will be using two table, one for actual user listing and second will contain the user types available with their IDs, those IDs from second table will be used in first one to specify each user's type or privileges level.


Table One Details:-
Table Name: user
Table fields are as follows:-
userID INT Auto-Increment
userName Varchar(100) Must be unique, used for login
password Varchar(100) Must contain MD5 encrypted password
userStatusID INT(3) The user type ID coming from "userstatus" table and will be used to assign previllages.
email Varchar(100)
userActive TINYINT(2) An optional field but if you choose to use it you can disable users from being login.
Name Varchar(45) User's Actual First and Second Name
Country Varchar(45)
Gender Char(1) 'M' for Male and 'F' for Female

Table Two Details:-
Table Name: userstatus
Table fields are as follows:-
userStatusID INT(3) Auto-Increment
userStatus Varchar(40)

Sample data for table two aka userstatus
1 Admin
2 Operator
3 Visitor

Before jumping on to the PHP actual authentication script next step for us to populate the tables. For data insertion into login table you will yourself design the form and PHP script I will just guide you with some most important things.

As I have given sample data for table two you will have to similarly do some brainstorming for identify how many user types you are gonna support in your login script and will have to just put in to "userstatus" table as given in above sample. After you are done with it now its time to make a form and php script to populate table one called "user".

While entering data into table one "user" choose user type of user by entering the "userStatusID" from userstatus table to "userStatus" field of "user" table. I mean if you are gonna enter a user who is "operator" so according to my sample data you will set the "userstatus" field of "user" table to '2'.

'userActive' field must be set '1' for an active user and '0' for disabled user, which you don't want this time to be able to get login.

Data in password field must be encrypted with 'MD5' encryption before entering it to the table. This can be easily done by a 'md5()' php function which will give you an encrypted string.
e.g see following how data is being encrypted while getting from user insertion form.

$password=md5($_POST['password']);

Now data in this $password variable will be entered in 'user' table's 'password' field. As the 'MD5' encryption is the one way encryption which can't be decrypted so even some one looking into db can't retrieve the password of the user. While user will get login you will again decrypt the password entered by user with md5 and compare it to md5 decrypted string coming from database to verify the correctness of password.


Now after making login form exactly according to specifications given above, lemme mention them again here, which are as follows.

Make a login form with two fields and one login button. First field must be named "username" and second must be named "password". Post form using method="POST" and action must be another page lets say called doLogin.php which will actually contain the login PHP code.
Its time to write the code in doLogin.php which will be as follows.


session_start();
// Following Include File called "config.inc.php" contains DB connection code so make such and include it here
include_once("inc/config.inc.php");

$userName = $_POST["username"];
$password = $_POST["password"];
$errMsg="";
if($userName != "" && $password != "")
{
$encryptPassword = md5($password);
$authSql = "SELECT userID,userStatusID FROM user
WHERE userName = '".$userName."'
AND password = '".$encryptPassword."'
AND userActive = 1";

$authResult = mysql_query($authSql)OR die('Couldn\'t Authenticate Visitor:'.mysql_error());
$authRow = mysql_fetch_array($authResult);
$userID= $authRow['userID'];
$userStatus= $authRow['userStatusID'];

if ($userID > 0)//If user with this username and password actually fetched from db
{
$_SESSION['USER_ID'] = $userID;
$_SESSION['USR_LOGIN'] = $userName;
$_SESSION['USR_STATUS'] = $userStatus;
//Redirect user after being login to a page where you want.
header("Location: mainPage.html");
}
else //User have entered either password or username wrong or he is disabled or does not exist.
{
header("Location: login.html?msg=invalid");
}
}
else
{
// The value of user name or password not entered
header ("Location: login.html?msg=missing");
}
?>

Up-till now we have complete the initial login process but one small but extremely important thing still remains is to check on every page that if user came here after getting login or just putted in the address. If he/she didn't came through the login then he/she must be redirected to the login page. So include following small piece of code in beginning for every page before every thing else and it will do it for us.


session_start();
if (isset($_SESSION['USR_LOGIN'])=="")
{
header("Location:login.html?msg=Login_Required");
}
?>

Now this will redirect user to login page if he/she didn't came after login.

While login process we had set another session variable called $_SESSION['USR_STATUS'] this will actually help us to enforce privileges after login.

For example a piece of content of page is if only for admin and as admin's user status ID is '1' we will put a simple check.



session_start();
if (isset($_SESSION['USR_STATUS'])==1)
{
//display admin content here
}
?>

Or for an operator


session_start();
if (isset($_SESSION['USR_STATUS'])==2)
{
//display Operator content here
}
?>

Now finally for logout make a page named logout.php and put a link to it on any page. When some one will click that link he will go to logout page and will automatically logout and will be redirected to another page. Content of "logout.php" will be as follows.


session_start();
$_SESSION = array();
session_destroy();
// Redirect to following page after logout
header("Location: index.html");//Change the page according to requirement
?>


Now go and implement this all stuff and enjoy new knowledge of being login and logout. So start playing with it.

Posted in |