In this tutorial we are going to learn that How to Make a Login Form with Session in PHP. These days almost every website require a Login System for their website to protect their precious data from unauthorized access. I try my best to explain every thing in this article. If you need any type of help you can freely ask by commenting below. Follow the following simple steps and your Login Page will be ready.

LIVE DEMODOWNLOAD

What is PHP Session?

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.

How to start Session in PHP?

<?php
	session_start();
	// Do Anything
?>

 How to Store values in PHP Session Variable?

<?php
	session_start();
	// to store session values
	$_SESSION['username']= $username;  // Initializing Session with value of PHP Variable
?>

 How to read values of PHP Session variable?

We simply need to echo (print) our initialized session as:

echo $_SESSION["username"];

 Let’s Move to Our Login Form

We need to create a HTML Form for user to input his username and password. I have create simple HTML Form below. If you want to chose your own design you can use it.

Database Structure

CREATE TABLE `users` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `password` varchar(50) NOT NULL,
  PRIMARY KEY (`uid`),
  UNIQUE KEY `username` (`username`)
)

PHP File: index.php

This file contain basic HTML form and some PHP code.

<?php
include('login.php'); // Include Login Script
if ((isset($_SESSION['username']) != '')) 
{
header('Location: home.php');
}
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" />  <br><br>
<input type="submit" name="submit" value="Login" /> 
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>

PHP File: connection.php

This file contain database configuration code. You have to change it with your server, username, password and database.

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

 

PHP File: login.php

This file contain main part of our login system.

<?php
session_start();
include("connection.php"); //Establishing connection with our database

$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];

// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);

//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);

//If username and password exist in our database then create a session.
//Otherwise echo error.

if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: home.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}

}
}

?>

PHP File: check.php

This file check whether the user is logged in or not. If user is not logged in it will redirect to index.php that is our login page. You can include this file to every file on which you can restrict user to log in.

<?php
include('connection.php');
session_start();
$user_check=$_SESSION['username'];

$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");

$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);

$login_user=$row['username'];

if(!isset($user_check))
{
header("Location: index.php");
}
?>

PHP File: home.php

This is your welcome page.

<?php
	include("check.php");	
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
<br><br><br>
<a href="logout.php" style="font-size:18px">Logout?</a>
</body>
</html>

PHP File: logout.php

This is your logout file that will destroy session and redirect user to index.php

<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}

?>

LIVE DEMODOWNLOAD

If you have any problem regarding to this post you can ask freely in comment 🙂

Updated 01/28/2015

Many readers were facing problem in installation of this script that I have given in download link. So here is the short video to learn how to install this script.

101 COMMENTS

  1. Good tutorial. But my problem is how to prevent a user who logged in once and logout now from logging in again because am creating a voting system and love to implement that idea of one time login

  2. You can create an extra field in database as ‘active’. Then on voting you can UPDATE that field to 0. And then on login you can check if that field is 0 or 1. If zero then print a message that you have cast a vote and so.

  3. i fund my problem in the tut the code from the login is:

    $username = mysqli_real_escape_string($db, $username);
    $password = mysqli_real_escape_string($db, $password);

    and in the download is

    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    the code from the download is wrong.

  4. Great script and tutorial. I am getting a problem where even when I put in the right credentials, I get “Incorrect username or password.” I’ve sent you my files via email if you can maybe take a look and help me out. Otherwise, great tutorial! Very helpful for somebody learning PHP like myself.

  5. I do not speak English. I would ask how it possible to just log in by entering the email instead of username. While giving the welcome showing the username. Thank you

  6. Thanks, but not it is working.
    I added:
    $email = $ _ POST [’email’];
    $email = stripslashes($email);
    $email = mysqli_real_escape_string($db, $email);
    $sql=”SELECT user_id FROM users WHERE email=’$email’ and password=’$password'”;
    and also
    if(isset($_POST[“submit”]))
    {
    if(empty($_POST[“email”]) || empty($_POST[“password”]))
    I also updated the form.

    What am I doing wrong ?

  7. Is there a solution to this? I have copied the code identically. I have updated the variables in connection.php to my own server (localhost) username (root) etc but when i click Login nothing happens. I have user details inserted in my users table. Please help

  8. Hi Michelle. Several of us are having the same issue. Even know connection details has been changed. There seems to be a problem with login code or page redirection as no errors are displayed either. Something is not right. Hopefully the author can review and find this out

  9. Hi Abdullah, I have emailed you my code, can you please help me, I am running out of time for my project. Thank you

  10. Thank you so much for your help. After watching the video I found where my error was. I wan not encoding the password with md5. Once again thank you.

  11. Author , why use

    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysqli_real_escape_string($db, $username);
    $password = mysqli_real_escape_string($db, $password);

    if mysql has mysqli_stmt_bind_param, which excludes injections?

  12. This is great! Thanks for the helpful code! Is it possible to add a “I forgot my password” function to this? I am really new to PHP and not sure where to even begin. Trying to think of a simple way to allow users to reset and change their passwords without involving an admin…if possible.

  13. Wasn’t working for me – ended up using !empty($_POST) instead of isset($_POST[“submit”]) then it worked.

  14. ¿ $login_user; or $username;?

    in post
    if(mysqli_num_rows($result) == 1)
    {
    $_SESSION[‘username’] = $login_user; // Initializing Session
    header(“location: home.php”); // Redirecting To Other Page
    }

    in file download
    if(mysqli_num_rows($result) == 1)
    {
    $_SESSION[‘username’] = $username; // Initializing Session
    header(“location: home.php”); // Redirecting To Other Page

  15. i was wondering why it wasnt working. Until I remembered that the password attribute uses md5. -_-

  16. for some reason though, the code suddenly isnt working when I changed the code for it to use my database instead of yours.

  17. Okay the problem is that I get redirected back to the index page from home after I entered the correct information into the form

  18. Hi, i am new here. Thank you very much for your tutorial. I had some problems when using it.

    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /Applications/AMPPS/www/…/login.php on line 27

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /Applications/AMPPS/www/…/login.php on line 32

    Therese are my errors.

    Then when I put the right username and password (md5 done before in db), Incorrect username or password pop up.

    Thank you very much.

  19. Hi!

    I like to add something with userlevels.
    If a user has level 1 it goes for example to test1 page and an user with level 3 goes to test2 page.
    Can you maybe help me out with that? would be great!

  20. Hi Rolinda, first you have to add a new column in your database. Then in login.php where we are redirecting user to home.php change query there using if else. Suppose you have added new column as status then it will be like:

    if(mysqli_num_rows($result) == 1)
    {
    $_SESSION['username'] = $login_user; // Initializing Session
    if($row['status'] == 1)
    {
    header("location: test1.php");
    }else
    {
    header("location: test2.php");
    }
    }

  21. Thanks for your fast answer!
    But it sends me all the time to test2 page. Even when im logging in with a status 1:(

    And on the check page, can there be a code to check on every page with status it has and when someone with status 1 can’t access a page that’s only accessible for someone with status 3? (status 3 can reach every page)

  22. had the same problem like the rest, it didn’t do nothing after entering credentials, i had to delete $password = md5($password); now it works fine!

  23. I copied everything over exactly, and used your table structure. The only change made was db login credentials. When I try to login I get these errors

    “Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/newadminipaplus/public_html/krill/try/login.php on line 27”

    “Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/newadminipaplus/public_html/krill/try/login.php on line 32.”

    I didn’t change anything on login.php so the line numbers will be the same as in your files. Any suggestion? Thanks for the tutorial

  24. never mind -fixed that error, still getting incorrect user name/password when I know they’re correct but hope to get this also resolved. thanks again

  25. Great stuff! It helps me a lot .. But what changes will come in check.php if I change the table field username with name

  26. For the people who did everything correctly but nothing is working not even errors are popping up: Remove the if(isset($_POST[“submit”])) statement from the login.php and the {} ofc and it should work fine…..

  27. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\project_1\login.php on line 27

    Warning: mysqli_num_rows() expects exactly 1 parameter, 2 given in C:\xampp\htdocs\project_1\login.php on line 32

    how to fix this

  28. I know this is an old post, but I found it and probably others will as well so I want to point out a couple of things.

    How can so many users be wrong in saying that this script doesn’t work?
    Well, maybe there is something wrong with the code in the tutorial?

    In index.php line 27 you need to add name=”submit” to the code:
    This is done in the project files for download. Without the name parameter nothing happens when you press submit because no POST variable is sent.

    And as another commented:
    In login.php line 34 you use: “$_SESSION[‘username’] = $login_user;”
    The variable “$login_user” is not set and it should be: “$_SESSION[‘username’] = $username;”

    It would be nice if the author acutally tested the code in the tutorial and not only the code in the attached files that is extensively modified compared to the tutorial above.

    Except for these details, thank you for a good tutorial!

  29. yo dude login worked flawlessly with your code. I have the Test account. Do you have a register form that would work with this already awesome script so i can make additional users?

  30. I followed your steps shown in video..
    Import sql table
    After setting user and password

    SET FOREIGN_KEY_CHECKS=0;

    — —————————-
    — Table structure for `users`
    — —————————-
    DROP TABLE IF EXISTS `users`;
    CREATE TABLE `users` (
    `uid` int(11) NOT NULL AUTO_INCREMENT,
    `username` varchar(50) NOT NULL,
    `password` varchar(50) NOT NULL,
    PRIMARY KEY (`uid`),
    UNIQUE KEY `username` (`username`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

    — —————————-
    — Records of users
    — —————————-
    INSERT INTO `users` VALUES (‘1’, ‘test’, ‘827ccb0eea8a706c4c34a16891f84e7b’);

    http://localhost/loginscript/

    gives the following error…

    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\loginscript\login.php on line 27
    Call Stack
    # Time Memory Function Location
    1 0.0010 246776 {main}( ) ..\index.php:0
    2 0.0010 255184 include( ‘C:\wamp\www\loginscript\login.php’ ) ..\index.php:2
    3 0.0040 266240 mysqli_fetch_array ( ) ..\login.php:27

    ( ! ) Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\loginscript\login.php on line 32
    Call Stack
    # Time Memory Function Location
    1 0.0010 246776 {main}( ) ..\index.php:0
    2 0.0010 255184 include( ‘C:\wamp\www\loginscript\login.php’ ) ..\index.php:2
    3 0.0760 266824 mysqli_num_rows ( ) ..\login.php:32

    Any idea????

  31. Its working now.

    I have another very important question. I need to embed this php, mysql code for user login system.
    Each user can see only his page. so basically, each user has

    name..passwaord and unique url (what he/she can see) …

    How can I do it.

  32. You really shouldn’t use MD5 password hashes and you really should use PHP’s built-in functions to handle password security. Make sure you don’t escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.

  33. You have to add new column in your database structure and after that put your desired URL depends on you whether you want to add in manually or else. And then in login.php change this code
    if(mysqli_num_rows($result) == 1)
    {
    $_SESSION['username'] = $login_user;
    header("location: home.php");
    }

    to
    if(mysqli_num_rows($result) == 1)
    {
    $_SESSION['username'] = $login_user;
    header("location:".$row['url']);
    }

    Let me know if it works or not.

  34. i try but does’nt work. i think its because my admin account is more than one, so we need while do to select every row.

  35. Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in /opt/lampp/htdocs/libraryman/login.php on line 15

    Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, string given in /opt/lampp/htdocs/libraryman/login.php on line 16

    Warning: mysqli_query() expects parameter 1 to be mysqli, string given in /opt/lampp/htdocs/libraryman/login.php on line 18

    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /opt/lampp/htdocs/libraryman/login.php on line 19

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /opt/lampp/htdocs/libraryman/login.php on line 20

    how to solve this? the table is filled

  36. When i put wrong usrname and password, it did shows “Wrong username and password”. But when i put right username and password, it immediately redirect back to index.php. looks like the problem is in check.php. when i remove the “include check.php” in home. It is working but the session is gone. How do i fix this?

  37. Still haven’t updated you code

    In login.php line 34 you use: “$_SESSION[‘username’] = $login_user;”
    The variable “$login_user” is not set and it should be: “$_SESSION[‘username’] = $username;”

    Made the adjustment and mine finally works….

  38. I’ve tried copying the code from the tutorial and downloading the code to run and get the same results either way. When I enter the correct username and password, test/12345, the script responds with “Incorrect username or password.” I watched the video and set up a new database to run this test with. The only difference between the video and my setup is the connection parameters to my database. I’m still finding differences in the code between the tutorial and the download files but neither of them work.

  39. How to add in the code? Restrict Pages From Non Admin Users? Restrict based on admin=level1, and user=level2? Thanks 🙂 !

  40. Sanel, you can add an extra column in your user table and assign a number to every user like 0 or 1, 0 for non admin user and 1 for admin. Then on every page you can check if the value of that column of logged in user is 0 or 1 and then you can redirect user to home page or any other page.

  41. Hello. I have changed the connection file to instead use my online db, But when i try to login in i get the following error. “Connect Error (2002) php_network_getaddresses: getaddrinfo failed: Name or service not known”, i am using the same database connections for another function where it works fine, the only difference is that your version is called from html, and the other version is called directly via url. Do you have any suggestions or ideas, what is causing the problem.

  42. I have a problem with the re-directs. Rizky (in the comments) had highlighted it but unfortunately you did not tackle it. The check.php loops in redirecting the user after logging in. Thus using chrome I get and ERR_TOO_MANY_REDIRECTS. I have also seen this via the developer tools (Google Chrome) the redirect loops indefinitely. Yet again, when I don’t include the check.php in the home.php i lose the session and anyone can access the page. Kindly assist.

  43. Abdullah,

    Just wanted to point out that the script you have available for “download” is very different to the script you have displayed up top in this blog post.

    Also, as noted in the replies above by Mike on July 1st 2016…

    In login.php line 34 you use: “$_SESSION[‘username’] = $login_user;”
    The variable “$login_user” is not set and it should be: “$_SESSION[‘username’] =$username;”

    I basically ran into the same issue everyone else seemed to have when they entered the correct information but all that happened was the index page reloaded – it never went to the welcome (home.php) page. As soon as I made the change detailed in Mike’s reply above, it corrected the issue and worked perfectly.

    I’m not sure if you intend to change the above blog post to match what you have available to download – but really all you need to do is make the change suggested in Mike’s reply and everything should work flawlessly.

    Other than that, thank you for making this tutorial, and for keeping it up for others to use…

    – E J Brady

  44. I tried to add second username or change password to first one… not working? how can you add more usernames and passwords for anyone who want to log in. I tried to edit on MySQL, or add username and password on phpmyadmin but nothing works. just this username and password you provided and it worked. (test and 12345).

  45. Nevermind, I got it… I watched your video again and again, and found that I just misfollowed your steps which you should have put ‘12345’ on the box at md5.cz instead of ‘test’ where it will encrypt the password to those numbers and etc and copy it, paste over there at phpmyadmin.

  46. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\login4\login.php on line 27

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\login4\login.php on line 32

  47. hello the code works perfectly, but you only echo the username, but i want to echo all user data relating to a certain user submitted during registration after user logged in…pls i need help thanks

  48. When I try your tutorial I get “Incorrect username or password.” even though I have an username and a password in my database. What have I done wrong?

  49. Why when I log in it keeps redirecting me to the login page? Its a constant loop. Help Needed ASAP Please!

Leave a Reply