[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!
how can create comments reporting as like this page?
This is my login code:
Inventory System
<?php
$login_form = <<<EOD
Username:
Password:
EOD;
echo “Please enter your Login Information”;
echo $login_form;
$msg = $_GET[‘msg’]; //GET the message
if($msg!=”) echo ”.$msg.”; //If message is set echo it
?>
And this is my check_login page:
This error displayed when i open the login page :
Notice: Undefined index: msg in C:\xampp\htdocs\inventori\login.php on line 18
when i try to not to enter any username or password, “Wrong Username or Password. Please retry” message will appear instead of “Please enter some username and password”. Can anyone help me to solve this prob? Thanks….
check_login page:
hi its nice.
thanks
neither the download link or demo link work!
Sir, I wanted to knw abt $login_form =<<<EOD . wht is meaning of <<<EOD ?? Otherwise, I loved this article . its very helpful in my project work. need to knw abt <<<EOD. reply soon as I have reporting of my project in my colg so I must knw abt it .
Sir, I wanted to knw abt $login_form=>>>EOD. can we use any other way to define $login_page? as I’m getting error on this line 8. error is Parse error: syntax error, unexpected T_VARIABLE in C:\wamp\www\project php\login.php on line 8. need its solution sir as soon as u can give reply.
the links for download and demo don’t work
greetings. thanks for the tutorial its very helpful ^^ i just want to ask if i have a register and log in. then use a session like you did in log in to create a profile like page.HOW can i fetch the data from table that i use in register so i can display the info on the profile page that is using the $_SESSION[username].
sorry newbie here. and sorry if i sound stupid.
again thanks in advance
I am having a similar issue as a few people in here. I have the code working fine with out errors. I have replaced session_registered with isset($_SESSION[‘name’]); and isset($_SESSION[‘name’]); — I have also entered in a username and a password with the function of SHA1 and changed the SHA to SHA on in the SELECT statement and I an still not able to login with the correct username and password in my database. Any ideas? Is there other code that needs to be replaced that is outdated. I have looked through the code numerous times and can not see anything that would cause me to not login successfully.
Garrick says:
August 23, 2011 at 2:05 am
Your comment is awaiting moderation.
I am having a similar issue as a few people in here. I have the code working fine with out errors. I have replaced session_registered with isset($_SESSION[‘name’]); and isset($_SESSION[‘name’]);
SORRY I meant Garrick says:
isset($_SESSION[‘name’]); and isset($_SESSION[‘password’]);
Hello, the links are not working for downloading
How to fix this issue ?
Fatal error: Call to undefined function mysqli_connect() in /home/cricnepa/public_html/profile/pro/config.php on line 7
HI,
i have created a website with log in page, but when i copy and paste my home page URL it’s entering to that page. How to block entering to my home page without using my home page.
Hi
Lovely tutorials.
Will you do an updated tutorial for the latest version of php or is that not necessary?
i like your website…
hello,
i’ve done whatever u said above and created all files n database table now my question is that now what should i do to add administrator part in my webpage. i’m a IT student and making project for to learn. plz help me.
define(DOC_ROOT,dirname(__FILE__)); // To properly get the config.php file
error is Parse error: syntax error, unexpected ‘<' in C:\wamp\www\EAD_project\check_login.php on line 2
why????????
Rocking articles .thank you for sharing ..
When I go to download or demo the system, the links are bad.
I know! I will update this with a new tutorial ASAP 🙂
Please update this example ,, as soon as possible
How can see online demo………..pls check…………
Hi,
Can you upload it again as the download link is broken
hi this is so nice code ………..
i have a problem in login page in php code..actually i’ve created this login page using class..where i’ve passed the select query then i made login page..then i have got my page run bt it’s not getting worked.could u help me pl
thank you so much. this tutorial helps me alot in my new website.
i want to know about javascript validation for php loginpage and registration page
On my next post I shall talk about js validation of forms
I am getting following error:
Notice: Undefined index: msg in C:\wamp\www\test\login.php on line 15
Is there another place where i need to define a default value.
thanks in advance.
seems all working fine and able to login but still 1 error coming from my admin page….
Deprecated: Function session_is_registered() is deprecated
Sorry dude but im totally unable to down the link :'( like y cant i man
sir i made a web page but one problem create . new user not login without register him/her self . this code send me sir
FYI…the session_is_registered() function is deprecated as of PHP release 5.3.0
Ref: http://php.net/manual/en/function.session-is-registered.php
Aloha,
badevilpenguin