[box type=”warning”]This post has been outdated. Please check the new one here where we have discussed how to create the system using session and cookie with remember me option.[/box]
In this tutorial we shall see, how to create a basic Login System in PHP using SESSION. We shall discuss, a fully secured login system with MySQL connectivity along with an Online Demo. The login system will redirect access to the admin file if not logged in! It will also show the current user name where ever you want [In the Demo page it is on the Page heading]
For those who are a little familiar with PHP, here is the download source code and Online Demo link
[box type=”warning”]This post has been outdated. Please check the new one here where we have discussed how to create the system using session and cookie with remember me option.[/box]
Account Login Details for the Demo page are:
- User Name: swashata; Password: swashata;OR
- User Name: admin; Password: admin
If you want to understand the coding behind the login system, then read on below…
#0: Strategy Used behind the Login System:
Here we shall use 5 files for making the whole system.
- config.php: The main file for holding the information related to the admin MySQL table. We shall discuss in brief how to create the table. For information do check the MySQL posts.
- admin.php: For administrative functions. It will redirect to login.php if not authorized already;
- login.php: A webpage for displaying form of login. It will submit the form to check_login.php where it will be processed further;
- check_login.php: A PHP script to check the login details from the MySQL Table. If successfully matched, then it will register the Session, else will redirect back to the login.php file with error message;
- logout.php: It will delete the session, and will redirect back to login.php file with success message;
#1: Setting up the MySQL Table:
We shall use a MySQL table like this for storing administrator information:
id | user_name | user_pass |
1 | admin | admin |
2 | swashata | swashata |
Basically we shall encrypt the password inside the table. Just for the demonstration I have showed the passwords above…
Now create a Database and inside it create a table login_admin with the following MySQL query command:
CREATE TABLE login_admin ( id INT NOT NULL AUTO_INCREMENT, user_name VARCHAR(100), user_pass VARCHAR(200), PRIMARY KEY (id) )
Now insert the two user information inside the table with the following command:
INSERT INTO login_admin (user_name, user_pass) VALUES ( ‘swashata’, SHA(‘swashata’) ) INSERT INTO login_admin (user_name, user_pass) VALUES ( ‘admin’, SHA(‘admin’) )
Now your MySQL table is ready for use!
#2: Setting up the config.php file:
As mentioned before, it just contains all the necessary MySQL Database connection information. Here is the code for this file:
<?php /********************************************************************** *Contains all the basic Configuration *dbHost = Host of your MySQL DataBase Server... Usually it is localhost *dbUser = Username of your DataBase *dbPass = Password of your DataBase *dbName = Name of your DataBase **********************************************************************/ $dbHost = 'localhost'; $dbUser = 'Data Base User Name'; $dbPass = 'Data Base Password'; $dbName = 'Data Base Name'; $dbC = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName) or die('Error Connecting to MySQL DataBase'); ?>
Just save this file with the above codes.
#3: Code behind the login.php File:
It shows up the login form and moves it to check_login for further processing!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Login Demo</title> </head> <body> <?php $login_form = <<<EOD <form name="login" id="login" method="POST" action="check_login.php"> <p><label for="username">Please Enter Username: </label><input type="text" size="100" name="username" id="username" value="Enter Username here" /></p> <p><label for="password">Please Enter Password: </label><input type="password" size="40" name="password" id="password" value="abracadabra" /></p> <p><input type="submit" name="submit" id="submit" value="Submit"/> <input type="reset" name="reset" id="reset" value="reset"/></p> </form> EOD; $msg = $_GET['msg']; //GET the message if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it echo "<h1>Please enter your Login Information</h1>"; echo $login_form; ?> </body> </html>
The $msg variable is used to show any message to the user using GET method.
#4: Code Behind the check_login.php file:
<?php define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file $username = $_POST['username']; //Set UserName $password = $_POST['password']; //Set Password $msg =''; if(isset($username, $password)) { ob_start(); include(DOC_ROOT.'/config.php'); //Initiate the MySQL connection // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($username); $mypassword = stripslashes($password); $myusername = mysqli_real_escape_string($dbC, $myusername); $mypassword = mysqli_real_escape_string($dbC, $mypassword); $sql="SELECT * FROM login_admin WHERE user_name='$myusername' and user_pass=SHA('$mypassword')"; $result=mysqli_query($dbC, $sql); // Mysql_num_row is counting table row $count=mysqli_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "admin.php" session_register("admin"); session_register("password"); $_SESSION['name']= $myusername; header("location:admin.php"); } else { $msg = "Wrong Username or Password. Please retry"; header("location:login.php?msg=$msg"); } ob_end_flush(); } else { header("location:login.php?msg=Please enter some username and password"); } ?>
As you can see it registers $_SESSION[‘name’] superglobal variable along with session_register and then redirects to admin.php. Now lets see what the admin.php file has to protect it from unauthorized use! Also note that if username and password do not match, then it redirects back to the login.php file with an error $msg.
#5: Code behind admin.php file:
<?php session_start(); //Start the session define(ADMIN,$_SESSION['name']); //Get the user name from the previously registered super global variable if(!session_is_registered("admin")){ //If session not registered header("location:login.php"); // Redirect to login.php page } else //Continue to current page header( 'Content-Type: text/html; charset=utf-8' ); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Welcome To Admin Page Demonstration</title> </head> <body> <h1>Welcome To Admin Page <?php echo ADMIN /*Echo the username */ ?></h1> <p><a href="logout.php">Logout</a></p> <!-- A link for the logout page --> <p>Put Admin Contents</p> </body> </html>
I have put comments every where! So you will be able to easily understand the code! Basically, here you need to be creative to put the admin contents properly! What ever it is, it will only be shown to authorized users. Also we have set a constant ADMIN to fetch the username from the super global variable $_SESSION[‘name’] and we can echo it where ever we want!
#6: Logging out with logout.php
It is used to destroy the current session. It is very simple!
<?php session_start(); //Start the current session session_destroy(); //Destroy it! So we are logged out now header("location:login.php?msg=Successfully Logged out"); // Move back to login.php with a logout message ?>
Save the file with the above code and you are done!
[box type=”warning”]This post has been outdated. Please check the new one here where we have discussed how to create the system using session and cookie with remember me option.[/box]
So, now you have successfully made a PHP login system using SESSION. Later we shall see how to use cookie and HTTP authentication to make personal login systems! I hope you have enjoyed this tutorial. Do give your feedback! If you face any problem, feel free to ask!
Hi,
I have the problem like this, Parse error: syntax error, unexpected ‘[‘ in F:\wamp\www\samp\protected\components\UserIdentity.php on line 21
what i do for next step? Plz help me.
Hi,
I have a problem like this, Parse error: syntax error, unexpected ‘[‘ in F:\wamp\www\samp\protected\components\UserIdentity.php on line 21
What i do for next step? Plz help me.
extra ‘[‘symbol has given in UserIdentity.php page in line 21, remove it and check code
hi Swashata, i am trying to implement ur admin login code but i always get the error saying that the admin user and password is wrong.
i had my login_admin table with the data in user_name as ‘admin’ and user_pass as ‘admin’but i cannot login into the admin page. so please help me immediately….
I have problem with download link and demo link, none of them are worked. please help with the right link.
thank you
bengkel
I need assistant with the php form for a login in php
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Password needed!
Username:
*
Password:
*
Type:
Select One……
Doctor
Nurse
Lab Tech
Accountant
Admin Officer
Security
Others
*
php code of two differnt level login page admin and
staff …and login page admin open differnt page and staff open differnt page
Untitled Document
body,td,th {
color: #000;
}
body p {
font-family: Georgia, Times New Roman, Times, serif;
}
body p {
color: #0F0;
}
#form1 table tr td {
color: #0F0;
}
#form1 table {
color: #00F;
}
#form1 table tr th h2 {
font-family: monotype Corsiva;
}
#form1 table tr td h2 {
font-family: monotype Corsiva;
}
#form1 table tr td h2 {
color: #000;
}
#form1 table tr td {
color: #000;
}
#form1 table tr th p {
color: #000;
}
Personl Information
First Name
Last Name
E-Mail
Age
Monday
Tuesday
Wednesday
Thursday
friday
Saturday
Sunday
/
Jan
Feb
Mar
Apr
May
June
Jul
Agus
Sep
Oct
Nov
Dec
/
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2013
2014
2015
2016
2017
2018
2019
2020
Sex
Male
Female
Other
Country
Pakistan
Kashmir
India
America
china
England
UAE
Login Information
User Name
Password
Corfirm Password
Hire me for this job 😛
I have a problem:
error is Parse error: syntax error, unexpected ‘<' in C:\wamp\www\EAD_project\check_login.php on line 2
in your coding extra ‘<'symbol is inserted in line 2 of your coding page..check it once
what is the use of login admin in php?
Very helpful, thanks a lot!
Is this system safe from using the username: admin
& the password: or”=’
???
Absolutely. Check the new tutorial. It is better 😉
thanks dude.
this tutorial awesome…I’ve been looking for something like this for a while.thanks for sharing
Pingback: Bookmarks for February 27th through March 1st | Peng's Blog
Thank you ! Swashata !
It is always good in helping out the people.
You are doing a good job i well appreciate you in posting wonderful tutorials helping newbies to learn basics.
I have read the all the comments people raised lot of problems.
I found there was only one error in this code which is causing not to inserting data into the mysql database in this code except everything ok working fine for me.
—————————————————
See The Error Here:
INSERT INTO login_admin (user_name, user_pass)
VALUES
(
‘swashata’, SHA(‘swashata’)
)
Fix: just remove that single in [‘swashata’,SHA(‘swashata’)] quotes and type it again from your keyboard.
then this query will execute successfully.
This was the one and only error that faced and rectified.
Guys i hope you understood Thank you !
Yours Ram.
I have problem :
Notice: Use of undefined constant ADMIN – assumed ‘ADMIN’ in C:\wamp\www\example\admin.php on line 3
Deprecated: Function session_is_registered() is deprecated in C:\wamp\www\example\admin.php on line 4
Welcome To Admin Page admin
Logout
Put Admin Contents
I hava problem :
Notice: Undefined index: msg in C:\wamp\www\example\login.php on line 15
Please enter your Login Information
Please Enter Username:
Please Enter Password:
hi,
i had inserted values in table of database, and i had given same v alues as user n pwd in select statement of query, after that wit same values i had logged in but for checking same values im getting “Wrong Username or Password. Please retry”. i checked everything in database and coding, but i didnt can u help
regards,
sri
Good 1 for beginners…
I have i doubt mentioned below ,if any 1 can understand it please forward the solution to me:
I have created som php pages for simple user login and matchind to databse in mysql.
I have used the session for log in and log out.
But. my doubt is that when i logged in and exit from browser without log out and come open the site again then also my session still running.
Why???
I read ,that by default when we exit from browser, session should destroy.
I have i doubt mentioned below ,if any 1 can understand it please forward the solution to me:
I have created som php pages for simple user login and matchind to databse in mysql.
I have used the session for log in and log out.
But. my doubt is that when i logged in and exit from browser without log out and come open the site again then also my session still running.
Why???
I read ,that by default when we exit from browser, session should destroy.
How far is this correct and why??
Your browser might be configured to retain the session information of your localhost.
1) error on Loging.php
Notice: Undefined index: msg in C:\wamp\www\temp\login\login.php on line 15
2) error on admin.php
Notice: Use of undefined constant ADMIN – assumed ‘ADMIN’ in C:\wamp\www\temp\login\admin.php on line 3
Deprecated: Function session_is_registered() is deprecated in C:\wamp\www\temp\login\admin.php on line 4
did any one help me to correct the error?
Hello,
Once I get enough time, I will repost it!
Pingback: Login Logout Admin & Remember PHP script using MySQL SESSION & COOKIE | InTechgrity