PHP Login Script with Session

Last modified on March 14th, 2017 by Vincy.

In this tutorial, let us see how we can implement authentication using a standard login form with session handling. Most of the website will have login script to provide user authentication. I will present you an example PHP code to implement authentication using a login script. With authentication, we can protect our website by filtering genuine users.

There are different ways to implement authentication and the most popular way is to using the login form and authenticate based on a username and respective password. Recently authentication using dynamically generated OTP is also becoming a norm and we will see about it in a coming tutorial.

In this tutorial, we are storing authentication credentials in a database. We will show a login form to enter login credentials. We compare the entered data against the user database. If match found, then the user is considered as authenticated. We use PHP session to preserve the logged-in state of the authenticated users. In previous tutorials, we have already seen about login via form submit and also via AJAX call.

PHP Login Sessions

We let the user submit their login credentials on a form and compare it with the user’s database. If a match is found, then we authenticate the user and store their logged in status by using the $_SESSION “super global”. For example, $_SESSION[“member_id”], $_SESSION[“display_name”]. This logged-in status will be preserved until the user logout. Once the user clicked the logout link, we clear his session by using PHP unset().

User Login Interface

First, we need to create login interface to allow the user to submit authentication information. It shows the username and password input fields in a form. On submitting this form, we post the values to PHP. The HTML and CSS code is as follows.

<form action="" method="post" id="frmLogin">
	<div class="error-message"><?php if(isset($message)) { echo $message; } ?></div>	
	<div class="field-group">
		<div><label for="login">Username</label></div>
		<div><input name="user_name" type="text" class="input-field"></div>
	</div>
	<div class="field-group">
		<div><label for="password">Password</label></div>
		<div><input name="password" type="password" class="input-field"> </div>
	</div>
	<div class="field-group">
		<div><input type="submit" name="login" value="Login" class="form-submit-button"></span></div>
	</div>       
</form>

and the styles are,

#frmLogin { 
	padding: 20px 60px;
	background: #B6E0FF;
	color: #555;
	display: inline-block;
	border-radius: 4px; 
}
.field-group { 
	margin:15px 0px; 
}
.input-field {
	padding: 8px;width: 200px;
	border: #A3C3E7 1px solid;
	border-radius: 4px; 
}
.form-submit-button {
	background: #65C370;
	border: 0;
	padding: 8px 20px;
	border-radius: 4px;
	color: #FFF;
	text-transform: uppercase; 
}
.member-dashboard {
	padding: 40px;
	background: #D2EDD5;
	color: #555;
	border-radius: 4px;
	display: inline-block;
	text-align:center; 
}
.logout-button {
	color: #09F;
	text-decoration: none;
	background: none;
	border: none;
	padding: 0px;
	cursor: pointer;
}
.error-message {
	text-align:center;
	color:#FF0000;
}
.demo-content label{
	width:auto;
}

PHP Login Script

We receive login form data in a PHP page as the post requests. In this script, we generate a SELECT query to validate user data with the database. If the user is authenticated successfully, then we add user logged-in status in a session and show a success message with the logout option to the user. The PHP login script is,

<?php
session_start();
$conn = mysqli_connect("localhost","root","","phppot_examples");
	
$message="";
if(!empty($_POST["login"])) {
	$result = mysqli_query($conn,"SELECT * FROM users WHERE user_name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
	$row  = mysqli_fetch_array($result);
	if(is_array($row)) {
	$_SESSION["user_id"] = $row['user_id'];
	} else {
	$message = "Invalid Username or Password!";
	}
}
?>

We can add this code on the same page above the HTML content or we can save it as an individual PHP file like login.php and add it to form action.

The code to show success message to the user is in the else part and the code is,

<?php 
} else { 
$result = mysqlI_query($conn,"SELECT * FROM users WHERE user_id='" . $_SESSION["phppot_demopage_459_user_id"] . "'");
$row  = mysqli_fetch_array($result);
?>
<form action="" method="post" id="frmLogout">
<div class="member-dashboard">Welcome <?php echo ucwords($row['display_name']); ?>, You have successfully logged in!<br>
Click to <input type="submit" name="logout" value="Logout" class="logout-button">.</div>
</form>
</div>
</div>
<?php } ?>

The “welcome message” will be displayed with the logged in user by their name and a link to logout to clear user login session.

And the code to logout is,

<?php
if(!empty($_POST["logout"])) {
	$_SESSION["user_id"] = "";
	session_destroy();
}
?>

Download

50 Comments to “PHP Login Script with Session”

  • ali says:

    Thanks for sharing , it helped me a lot in my little project.

  • swapnil says:

    can you pls share the sql file with download.
    thx

    • Gideon Birimuye says:

      Hi swapnil, hope you are doing great.The sql file below might be of help to you, i exported it using phpMyAdmin. You can copy it and save it as an sql file using any software (notepad, notepad++,Dreamweaver) any that you feel comfortable with and then import it in phpMyAdmin and then play with vincy’s scripts. Have fun.

      — phpMyAdmin SQL Dump
      — version 3.2.0.1
      http://www.phpmyadmin.net

      — Host: localhost
      — Generation Time: Dec 22, 2013 at 06:52 AM
      — Server version: 5.1.36
      — PHP Version: 5.3.0

      SET SQL_MODE=”NO_AUTO_VALUE_ON_ZERO”;


      — Database: `login_script`

      — ——————————————————–


      — Table structure for table `users`

      CREATE TABLE IF NOT EXISTS `users` (
      `user_id` int(11) NOT NULL AUTO_INCREMENT,
      `user_name` varchar(10) NOT NULL,
      `password` varchar(3) NOT NULL,
      PRIMARY KEY (`user_id`)
      ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


      — Dumping data for table `users`

      INSERT INTO `users` (`user_id`, `user_name`, `password`) VALUES
      (1, ‘Gideon’, ‘fox’);

    • Gideon Birimuye says:

      Swapnil remember i changed the name of the database to login_script. Keep in touch if you need more help.

  • Kumara says:

    Great work!

  • Wan says:

    My fault, I am missing a row in SQL. it should be OK now.. :)

  • Wan says:

    Hi, the page is not redirect to dashboard.php?
    atm.ssiunitek.com
    user: w09
    pass: 123

    Thanks

  • Akinsola says:

    good work Vincy,
    Thank you soo much

  • kevin says:

    hi,,,tnx alot…but still i have a problem in connecting into the database,,,the message INVALID will always pomp up…how can you advice me?

    • Vincy says:

      Hi Kevin,

      $conn = mysql_connect(“localhost”,”root”,””);

      Replace host,username and password specified for mysql_connect(), with your server config.

  • Lee says:

    Love the tutorial, I have a problem though. When I click submit it takes me to the User Dashboard but it is a blank page that just says ‘User Dashboard’ at the top.

  • Kalidoss says:

    Hi
    Am Kalidoss from India.
    this article very useful for me.. Thank you so much.Am always expecting your new update.

  • ragu says:

    logout session not work on mine for some reason i run the code as downloaded form here so i dont know why its not working. i can login in fine but its the login out thats not working

  • arun says:

    hello
    i have tried this code
    but i am getting following warnings
    1. message is not defined in
    2.Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

    • Vincy says:

      Hi Arun,

      @Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

      This is because of query failure. Before executing this query, ensure that you have users table with respective columns in database, as specified in code.

      @message is not defined in

      We have to define $message before we use. Otherwise, we need to check $message whether it is set or not. For example,
      if(isset($message)) echo $message;

  • Gideon Birimuye says:

    Vincy thanks for the sharing, it was really helpful. keep it up.

  • saiful islam says:

    i am know of ur form mining but i can’t show error message in the login page($messgae variable data), when i run the login form with wrong information but doesn’t show the message. The message area show all time in this message(Notice: Undefined variable: message in D:DIUwampwwwphptotal_loginIndia_loginformindex.php on line 9 ). How to show check validation message in the login page. Please suggest me. Thanks

  • sumit says:

    Hi vincy.
    This tutorial helped me alot .
    I would now like to know how do we display the name of the user logged in by hiding the login or signup button and they should reappear when the used loggs out. I have gone through many sites but could not understand.
    Would u plz write a code that would help me?

    • Vincy says:

      Hi Sumit,

      To display logged in username instead of login button,

      if($_SESSTION[“username”]) {
      echo $_SESSTION[“username”];
      } else {
      // display login button
      }

      Make sure, you have stored logged in user name into a session variable while login.

  • vhinzlloyd says:

    hi ,,thank u very much,,but i still have problem..ive noticed when i logged out,,and press back it will got an error,,like this Notice: Undefined index: user_name in C:\xampp\htdocs\experiment\samplelogin\user_dashboard.php on line 18
    .please help

    • Vincy says:

      Hi vhinzlloyd,

      If you check user_name session like,

      if(isset($_SESSION[“user_name”])) {

      instead of

      if($_SESSION[“user_name”]) {

      you can avoid this error notice.

  • Sjoerd says:

    I keep getting ‘Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in x at line x’

    How can I fix this?

  • Vincy says:

    Hi Michal,

    Thank you for the comment.

    This tutorial is just to explain login to storing user credentials into session.

    We can enhance this code by adding,

    • Validation to avoid SQL injection.
    • Javascript/Server side validation to prevent HTML code or other escape sequences.
    • We can log repeated invalid login attempts to stop anonymous by IP address.

    and etc. to avoid the security risks. But it will enlarge the code and loose the focus on topic.

    Security is more important and let us have separate tutorials to learn how to safeguard from security risk.

    Thank you for raising this point.

  • carlos says:

    hi and thanks for the article it is simple and easy-to-understand
    but i have a question here in the login redirect part line #4

    if(count($_POST)>0)

    is it possible to use isset instead of count ?? thanks again.

  • Himmat says:

    THANKS

  • banu says:

    hi,
    can yu pls help me wid dis error
    ” Notice: Undefined index: user_name in C:\xampp\htdocs\b\try\application\views\scripts\index\login.php on line 16 “

  • Rich says:

    Hi, im having trouble with session variable is not passing to the next page,
    The code i have is very similar to yours except a few security tweaks
    heres my bits n pieces

    //Register session variable after db check on authlogin.php page –
    ———————————
    $_SESSION[‘u_name’] = “myusername”;

    header(“location:summary.php”);
    }
    else {
    echo “Wrong Username or Password”;
    }
    ———————————

    And to validate on the account summary page –
    ———————————
    if($_SESSTION[“u_name”]) {
    echo $_SESSTION[“u_name”];
    } else {
    header(“location:index.php”);
    }
    ———————————

    Any help is much aprecciated :D

  • ron says:

    I want ask 1 question..how to select multiple table from single database to login..?example table group1,group2 and group3.so what php code for this?.

  • jorx says:

    hi these is the error i’m getting

    Notice: Undefined index: user_name in D:\xampp\htdocs\login\login.php on line 14

  • Jayamaha says:

    Thank u so much …

  • anu says:

    thx it was nicely xplained.but im having a problem with logout.
    when i logged out and press back button it will again redirect to the user’s account page(Previous Logged in page);
    this is the logged out code

  • David says:

    Thanks, cool stuff keep it up!

  • ganesh says:

    Thanks for tutorial…its great.

  • Mincy Varghese says:

    Can anyone help me ?.. I need to store all login details in a database.. somebody plz share me the coding if you have

  • ganesh says:

    Nice article for beginners like me.

  • Aggrey says:

    Pretty ideas, The guide saved me out. Oh,Thx alot.

  • PHP Training says:

    This is one of the best place to learn about web designing especially php and mysql.

  • PHP Training says:

    This is one of the best blog for developing login form using script. thanks vincy.
    by mathivel (php developer)

  • sakura says:

    thanks it is very helpful and informative… =D

  • Maffix says:

    Thanks for sharing the wonderful made code.

    It saves my day..

    Chers

Leave a Reply to sakura Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this Article