How to use session in login form in php

Firstly, the PHP documentation has some excellent information on sessions.

Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt() hashing function. This means that if any credentials are compromised, the passwords are not readily available.

Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.

You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.

To start a PHP session, you need to call session_start(). Similarly, to destroy a session and its data, you need to call session_destroy() (for example, when the user logs out):

// Begin the session
session_start();

// Use session variables
$_SESSION['userid'] = $userid;

// E.g. find if the user is logged in
if($_SESSION['userid']) {
    // Logged in
}
else {
    // Not logged in
}

// Destroy the session
if($log_out)
    session_destroy();

I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there.

Updated on July 1, 2020

by Neeraj Agarwal

Session variables are used to store individual client’s information on the web server for later use,  as a web server does not know which client’s request to be respond because HTTP address does not maintain state.


How to use session in login form in php


This tutorial enables you to create sessions in PHP via Login form and web server respond according to his/her request.


To Start a PHP Session:


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

To Store values in PHP Session variable:


<?php
session_start();
// Store Session Data
$_SESSION['login_user']= $username;  // Initializing Session with value of PHP Variable

To Read values of PHP Session variable:


<?php
session_start();
// Store Session Data
$_SESSION['login_user']= $username;  // Initializing Session with value of PHP Variable
echo $_SESSION['login_user'];

To Unset or Destroy a PHP Session:


<?php
session_destroy(); // Is Used To Destroy All Sessions
//Or
if(isset($_SESSION['id']))
unset($_SESSION['id']);  //Is Used To Destroy Specified Session

In our example, we have a login form when user fills up required fields and press login button, a session will be created on server which assigns him a unique ID and stores user information for later use.


Watch out live demo or download the given codes to use it.

How to use session in login form in php



Complete HTML and PHP codes are given below.

PHP File: index.php 
Given below code creates an HTML login form.


<?php
include('login.php'); // Includes Login Script

if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h2>PHP Login Session Example</h2>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>

PHP File: login.php
Consists of login script in which PHP session is intialized.


<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>

PHP File: profile.php
It is the redirected page on successful login.


<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout"><a href="logout.php">Log Out</a></b>
</div>
</body>
</html>

PHP File: session.php
This page, fetches complete information of the logged in user.


<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>

PHP File: logout.php
To destroy all the sessions and redirecting to home page.


<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: index.php"); // Redirecting To Home Page
}
?>

My SQL Code Segment:

To create database and table, execute following codes in your My SQL .


CREATE DATABASE company;
CREATE TABLE login(
id int(10) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
)

CSS File: style.css

Styling HTML elements.


@import http://fonts.googleapis.com/css?family=Raleway;
/*----------------------------------------------
CSS Settings For HTML Div ExactCenter
------------------------------------------------*/
#main {
width:960px;
margin:50px auto;
font-family:raleway
}
span {
color:red
}
h2 {
background-color:#FEFFED;
text-align:center;
border-radius:10px 10px 0 0;
margin:-10px -40px;
padding:15px
}
hr {
border:0;
border-bottom:1px solid #ccc;
margin:10px -40px;
margin-bottom:30px
}
#login {
width:300px;
float:left;
border-radius:10px;
font-family:raleway;
border:2px solid #ccc;
padding:10px 40px 25px;
margin-top:70px
}
input[type=text],input[type=password] {
width:99.5%;
padding:10px;
margin-top:8px;
border:1px solid #ccc;
padding-left:5px;
font-size:16px;
font-family:raleway
}
input[type=submit] {
width:100%;
background-color:#FFBC00;
color:#fff;
border:2px solid #FFCB00;
padding:10px;
font-size:20px;
cursor:pointer;
border-radius:5px;
margin-bottom:15px
}
#profile {
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7
}
#logout {
float:right;
padding:5px;
border:dashed 1px gray
}
a {
text-decoration:none;
color:#6495ed
}
i {
color:#6495ed
}


How to use session in login form in php


Conclusion:
Through Login/Logout form it becomes easy to deal with sessions in PHP. Hope you like it, keep reading our other blogs.

352 Replies to “PHP Login Form with Sessions”

  1. currently studying your tutorial, the reference to the sheet style is wrong ( or the name form_value.css is ) you have to make the change to see the page stylized

    Reply

    1. Reply

      1. Could put a tutorial on how to create a registration form together with the login and log out form

        Reply

      2. Can you kindly let me know how to get the login.sql fille

        Reply

    2. hello ,
      it’s not working i need your help

      Reply

      1. Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in C:AppServwwwlogin.php on line 1522
        how can i fix it

        Reply

        1. Hi Baskal,
          I guess there is a syntax error at end of line no. 1522, please make sure complete the line with “;”

          All the best !

          Regards,
          Ajmal

          Reply

  2. Hey guys i was wondering if somebody could help me to set up my database . Apparently Im doing something wrong. i´m just getting crazy trying to figure it out. Please help!

    Reply

    1. Hi Josefo
      Thanks for reading this blog you can setup database by following steps
      1) Go to http://localhost/phpmyadmin
      2) Then create new database “company”
      3) Import login.sql file which you will find in downloaded project’s folder

      Reply

      1. Hi admin,
        Could you please tell me how to connect dreamweaver to web server. I have copied the data from your site and paste it in dreamweaver but if i double click the file it’s not working.

        I am new for this php and all those things. So, kindly please anyone help me out for this problem.?

        Thanks in advance,
        Kumaresan S

        Reply

  3. Hi

    I have copied your script straight to my server and changed the DB username from “root” , “”
    to my own details for login

    I have the DB “company” and the tables from your sql file imported, everything looks fine until I attempt to login, no matter what I use, alex, fugo, formget etc it returns Username or Password is invalid

    Please help

    Running windows &
    IIS 7.5
    PHP 5.3
    Mysql

    Reply

    1. create DataBase in your table which will be fetched by your code.

      Reply

  4. very nice article dear

    Reply

  5. Thanks.

    Works like a charm 😀

    Reply

  6. Thanks. maybe this code can help me 🙂

    Reply

  7. Great tutorial. Helped me a lot 🙂

    Reply

  8. i run your sample code sent into my email but I cant run the php files. It does not view the result or show the php code as text form as it is

    Reply

    1. Hello Tarun mukherjee

      First unzip downloaded file and copy it on your local server
      if you are using wamp then copy here
      C:/wamp/www
      for xamp
      C:/xampp/htdocs

      Do the following steps for database setup
      1) Go to http://localhost/phpmyadmin
      2) Then create new database “company”
      3) Import login.sql file which you will find in downloaded project’s folder

      Now open your browser and run index.php
      http://localhost/login-form-php_download/index.php

      Reply

  9. great very simple and helping

    Reply

  10. NICE very helpful thanks a lot…………

    Reply

    1. Reply

  11. my code arent working that the error message i got.

    Reply

  12. I Was just wondering if someone could make me with a php script that works with this to register for a account?

    Reply

  13. You guys er really encouraging us keep it up i personally appreciate you all bye for now . . .

    Reply

  14. Very nice article. it is working properly.
    Thank you

    Reply

  15. THANKS you have givin important knowledge very easy way

    Reply

  16. Hello to every body, it’s my first go to see of this website; this weblog consists of amazing and genuinely fine information in support of visitors.

    Reply

    1. Hello E & Omissions..

      Thank you so much for your appreciation…!

      Keep reading our other blog posts.. for getting more coding tricks..

      Regards,
      FormGet Team

      Reply

      1. can you provide a newer code using mysqli instead of mysql

        please
        thank you before

        Reply

  17. Thanks man 🙂

    Reply

    1. Reply

  18. Why the password i enter (Eg: alex or ALEX) still can login by using your script?…in your demo only password (Eg: alex) can login…

    Reply

    1. Hello Kabuto,

      First you need to store login details in your database.

      Depending upon it , you will be able to login , and your script will work.

      Regards,
      FormGet Team

      Reply

  19. “Username or Password is invalid”

    I have stored the login details in the database and I still get this error. Any clue?

    Reply

    1. Make sure that you have created the database as “Company” , table as “login” ,

      column one as “id” , two as “username” and third as “password”.

      Reply

      1. hello admin i created the database named “company” and Table “login”
        include 3 fields “id” ” username” ” password”

        But the same error occurs again

        “INVALID USER NAME AND PASSWORD”
        Kindly help me how to solve this problem. Thanks in advance

        Reply

        1. Make sure that you have stored some data into the table. Like username as alex and password 123.

          And try to login it with same detail, but before login check whether data is inserted into database or not.

          Reply

  20. Thank you very much.
    very use full to me.

    Reply

    1. Hello Asbar,

      That sounds really great ! Keep reading our other blog posts for getting more coding tricks.

      Checkout new blog posts now : https://www.formget.com/blog/

      Regards,
      FormGet Team

      Reply

  21. Great tutorial, it’s helped me a lot!

    I do have a beginner’s question, however.

    I can’t seem to figure out how to pull and show the rest of my user’s database. For instance, in my database, I not only have a user name, but also their name, age, location etc…

    I would like to display it all respectively, once each user has logged in. Could you tell me how to do that?

    Any help would be appreciated. Thank you.

    Reply

  22. Hai sir i use ur code but
    this warning error is displaying

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in 24 line

    what can i do. pls help me

    Reply

    1. Hello Muthu,

      This is because , of database issue. Remember you need to create a database naming ‘company’ and table as ‘login’ with the column as id , username and password.

      That will work fine.

      Regards,
      FormGet Team.

      Reply

    2. I changed the
      if ($rows > 0) {
      and it worked

      Reply

  23. session did not working.. plz help

    Reply

    1. Hello Nitesh,

      Could you please let me know that what error you are getting while executing the code, so that I can help you out.

      Thanks & Regards,
      FormGet Team.

      Reply

  24. Nice information

    thank you

    Reply

    1. Glad to have a reader like you !

      Your words matters a lot for us.

      Thanks & Regards,
      FormGet Team.

      Reply

  25. I had same error message as Ebenezer.

    In my case, it has been caused within login.php by:
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);

    Once I marked it as comment my access worked. However now we have the issue with the “open door” for sql-injection ….
    // $username = mysql_real_escape_string($username);
    // $password = mysql_real_escape_string($password);

    Maybe this hint helps to find workaround.

    Reply

    1. Place the localhost connection before that :

      //Establishing Connection with Server by passing server_name, user_id and password as a parameter
      $connection = mysql_connect(“localhost”, “root”, “”);

      // To protect MySQL injection for Security purpose
      $username = stripslashes($username);
      $password = stripslashes($password);
      $username = mysql_real_escape_string($username);
      $password = mysql_real_escape_string($password);

      Hope it will work for you.

      Reply

      1. I copied the code,saved it as the said file extensions,but this always happens whenever I type in the correct password.

        Fatal error: Call to undefined function mysql_connect() in C:\ApacheServer\htdocs\login.php on line 14

        Reply

  26. Very cool, this is exactly what I was looking for?! I just made a rather lame login page yesterday without sessions etc and this helps me get to the next level. Sorry you will get lots of questions that are a bit out of scope- problems with mysql, problems with making sure they are using a webserver to serve up the page rather than opening it directly with a browser, windows paths etc. I’m on a mac and this was ridiculously easy to setup.

    Thank you!
    Ross

    Reply

  27. In Login.php, you are using mysql_real_escape_string before establishing a connection to the db.

    From the manual:
    Note:
    A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn’t defined, the last MySQL connection is used.

    http://php.net/manual/en/function.mysql-real-escape-string.php

    Reply

    1. The required changes has been done !

      Thank you so much for intimating us about this.

      Regards,
      FormGet Team.

      Reply

  28. great job .nice code very neat and clean.for beginners thats the best way to learn form handling with php .i would like to see some validation on form data.

    Reply

    1. Hello Pankaj,

      Thankyou so much for such a wonderful appreciation !

      To apply validations in form fields , kindly followup this post : https://www.formget.com/php-contact-form/

      Hope that will help you for that.

      Regards,
      FormGet Team.

      Reply

  29. Thanks for this code.Its great help for me .I was searching for code help like this….Once again thanks..

    Reply

    1. Reply

  30. thak you for the code.please help me to solve the error
    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\shinu\login.php on line 24

    Reply

    1. Hello Shiu,

      This is because , of database issue. Remember you need to create a database naming ‘company’ and table as ‘login’ with the column as id , username and password.

      That will work fine.

      Regards,
      FormGet Team.

      Reply

  31. thanks for your good knowledge

    Reply

    1. Reply

  32. thanks sir your hellp me in website

    Reply

    1. Hello Vikram,

      Pleased with your response. Keep following our latest posts for coding tricks and knowledge.’

      Regards,
      FormGet Team.

      Reply

  33. Hey I love this code. It works for me but I have two issues and one thing that I need for it. When ever I reach the log in page the sever credentials (root & password) are in the input fields. The server I’m using is xampp. Once I click in the fields and delete the user name root the password disappears and placeholder in the form username and password that I have in the code now appears. The other issue that I have is after logging out and it goes to the goodbye page if I should click the back button the page goes back to the login page (and of course root and the password are shown) but once you enter the username and password and click login it does nothing. To resolve that I made the goodbye page redirect to my homepage and not the login page. Even though that solved it I feel that the issue may affect something else. An addition that I would want for my user login is to have them go to individual pages. I’m building a photography site and want clients to be able to see their photos and be able to select which photo they want printed. So when a specific user logs in they are redirected to their profile page that only they have access to. Do I in the php that check the login credentials add multiple if statements for different users to redirect them to specific pages or what. So that this was a long posted question.

    Reply

    1. I was able to research the issue and sorted out the issue. The problem with the input fields being filled was a browser issue, so i placed a code to prevent that.

      Reply

  34. Respected Sir…

    I found your tutorial very helpfull…

    how can i create a feed back system..like yours comments page. i need such a page for my website.

    Other think that i wanna mention is how to use bootstrap in website.

    Regards
    Awal Khan (Pakistan)

    Reply

    1. Hello Awal,

      Right now we do not have any such tutorial , but i will let you know in future when we will create any.

      Anyways thanks for reading the post and liking it.

      Regards,
      FormGet Team.

      Reply

      1. Respected Sir,

        Is it possible to create an admin panel in a website, in which various interfaces are provided to end users. so they can publish their data easily..

        for example a school website.. in which a news are announced in notice board..

        I want to know, how to provide interface to end users and in which he/she posted the news which is then appeared in notice board page of site…

        it is requested form yours that:
        please refer me a link or some meaningful arguments about such system.

        All the friends are requested that please help me in this regard..

        Regards
        Awal Khan
        Pakistan

        Reply

  35. heey its very usefull for me thanks. But i want to ask you how to block the user if you was login you can’t go acces the login page? Thanks

    Reply

  36. Hi… Thank you for this great tutorial.. Can you please post the tutorial of uploading image and save it in a local folder?

    Reply

    1. Hello Divya,

      Pleased with your response.

      Here is the link where you will find number of tutorials for image upload :
      https://www.formget.com/?s=upload+image

      Hope I have helped you.

      Regards,
      FormGet Team.

      Reply

  37. Good Tutorial dear. Keep it up.

    How to extend this example to destroy the session after some specific interval of time ?

    thanks.

    Reply

    1. Hello Khan,

      Use this code to destroy session and to remove all session variables.

      // remove all session variables
      session_unset();

      // destroy the session
      session_destroy();

      Hope that will help you.

      Regards,
      FormGet Team.

      Reply

  38. Hello,

    That sounds really great ! Keep reading our other blog posts for getting more coding tricks.

    Catch up new posts from here

    Regards,
    FormGet Team

    Reply

  39. Hey Amin
    I am trying to develop A database window application,I have been using help from here…Thanks.But i only have one problem,I dont know how to convert Mysql and php into an executable standalone app..Please help ASAP as i am getting close to my deadline.

    Reply

    1. I will be glad if u help.

      Reply

  40. Why this code in my case wont work with second user . My first user works but when i add second user username and password :: Username or Password is invalid? Is this some issue.

    Reply

    1. Hello MIlos,

      Thank you so much for reading the post.

      I have checked it at my end and found it to be working fine.

      Let me know if any doubt persists.

      Regards,
      FormGet Team.

      Reply

      1. This is my little changed login , because of db fields>>> Can u see something wrong

        Reply

        1. Reply

          1. O stupid sorry when I edited I confused $username and $password, and for test I enter same username and pass
            for the first one now is corrected.
            Thanks nice work!

  41. Thanx Team Formget U Guys Doing Best

    Reply

  42. How to turn off usrname and password autocomplete?

    Reply

  43. You article is the bomb…I wish i could pay for every second i spent reading this

    Reply

  44. very good and easy undestanding login code thank you
    no my web site but required domain name foe website
    thanks good by

    Reply

  45. this is very nice

    Reply

  46. it shows the warning as mysql_real_escape_string access denied using password no how to resolve this error

    Reply

    1. after logging it is not displaying profile page. what could be the reason?

      regards
      nitesh

      Reply

  47. i have know php

    Reply

  48. i want to make logstic registration form
    plz send me code kindly

    Reply

  49. Hello 🙂

    I have copied your script straight to my server and changed the DB username from “root” , “”
    to my own details for login

    I have the DB “company” and the tables from your sql file imported, everything looks fine until I attempt to login, no matter what I use, alex, fugo, formget etc it returns Username or Password is invalid

    Please help

    Reply

  50. very informative..thanks

    Reply

  51. Lovely clean look to your site and form. However, rooting through your code I saw some issues:

    mysql_* functions: deprecated. You should use mysqli or PDO prepared statements and bind values/ parameters.

    passwords: being stored as plaintext. They should always be stored as a hashed value. Newer versions of PHP use the password_hash() and password_verify() functions.

    css: absolute values throughout. Difficult to work with absolute values like pixels for certain dimensions if developing a responsive form. Consider using % and rem.

    Reply

  52. Hi! I used all of your sample code and used the SQL, so therefore I have created a company database and login table. However, when I hit submit, it just stays on the same page and does nothing? I’ve tried changing the redirect page but still nothing. I’ve had this with other samples from different sites too

    Reply

    1. I’m having the same issue and cannot figure it out

      Reply

    2. Hello Jess

      Thanks for sharing your problem with us.

      First unzip downloaded file and copy it on your local server
      if you are using wamp then copy here
      C:/wamp/www
      for xamp
      C:/xampp/htdocs

      Do the following steps for database setup
      1) Go to http://localhost/phpmyadmin
      2) Then create new database “company”
      3) Import login.sql file which you will find in downloaded project’s folder

      Now open your browser and run index.php
      http://localhost/login-form-php_download/index.php

      Insert username-formget and password-formget or username-fugo and password-fugo if you want to make your own username and password please insert first it on company database’s login table.

      Thanks & Regards,
      FormGet Team.

      Reply

  53. This paragraph will help the internet users for
    creating new weblog or even a weblog from start to end.

    Reply

  54. so useful……i dont know about thae php.now i learn little bit.

    Reply

  55. thanks a lot.. it helps me a lot..

    Reply

  56. Isnt there supposed to be an on click code? For the login button?

    Reply

  57. session. php file must be included in evry page of my site to remain log in the site?

    Reply

  58. Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\prac\index.php:2) in C:\xampp\htdocs\prac\login.php on line 2

    Reply

    1. Hello cyden

      Thanks for sharing your problem with us.

      Write ob_start() before session_start() statement.
      Look at below code for solutions.

      ob_start();

      This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer

      Thanks & Regards,
      FormGet Team.

      Reply

  59. It is very nice, clear code and saving my time. it works well.
    Thank you. Thank you…

    Reply

  60. Hello Pangan

    Thanks for sharing your problem with us.

    Write ob_start() before session_start() statement.
    Look at below code for solutions.

    < ?php @ob_start(); session_start(); ?>

    ob_start();

    This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer

    Thanks & Regards,
    FormGet Team.

    Reply

  61. thank you

    Reply

  62. this is good for beginners i really like this work good man keep it up dear.
    Harry!
    you must enter user name and password in database record then try to log in

    Reply

  63. your post and website is great but would appreciate if you could update the code to sqli or pdo format, as sql will become invalid

    Reply

  64. i m new in php, your article is very intuitive, i adapted the code to run with postgres, it work very fine, thx e lot.

    Reply

  65. I have created the login form but when submit, it just gives me a page of the above php code.

    Reply

  66. You are doing such a great work.
    Your tutorial is helpful for me.
    I want to ask you that is that possible that if i logged in and go to profile age then login page never open till i am logged in.
    I mean to say that after login and go to profile.php if i opened login.php then it will redirect to profile.php
    Thank you.

    Reply

  67. I enter username & password but not redirecting of profile page.. what to do????????

    Reply

    1. I’m having the same problem. Any idea how to fix it?

      Reply

  68. thanks for useful site,it’s okaaaaayyy.
    but when i run codes;

    error of The mysql extension is deprecated and will be removed in the future

    Reply

    1. Merry Christmas and a hapy new year.

      Reply

  69. Thankyou..:)

    Reply

  70. Hi, how can I show the corresponding data of each user and ONLY his own data registered on db? I mean, I’d like the user to see only his own registers when a select is performed.

    Reply

    1. Reply

      1. Ya, this simple queries are easy. But I have 2 tables (login and events) and I want the user from login table to display his own events from events table. I read something about INNER JOIN but it’s not working. Do I have to add any other id/key when the event is inserted?

        Reply

        1. here is my code:

          Untitled Document

          query($sql);

          if($result->num_rows > 0){
          while($row = $result->fetch_assoc()){
          $id = $row[‘id’];
          echo “”;

          echo “”;

          echo “”.””;
          echo “”.$row[‘event_name’].””;
          echo “Local:”;
          echo “”.$row[‘event_place’].””;
          echo “Data:”;
          echo “”.$row[‘event_date’].””;
          echo “Hora:”;
          echo “”.$row[‘event_time’].””;

          echo “”;
          echo “”;

          echo “Vip Antecipado:”;
          echo “”.$row[‘vip_ant’].””;
          echo “Normal Antecipado:”;
          echo “”.$row[‘normal_ant’].””;
          echo “Vip no local:”;
          echo “”.$row[‘vip_local’].””;
          echo “Normal no local:”;
          echo “”.$row[‘normal_local’].””;
          echo “Mais informações:”;
          echo “”.$row[‘obs’].””;
          ?>
          <a href="excluir.php?id=”>Excluir
          <?php

          }
          }else{
          echo "Oops! Nenhum evento seu está cadastrado ou já foi realizado.";
          echo "setTimeout(function(){
          window.location.href=’user_panel.php’;
          }, 3000);”;
          }

          echo “”;

          echo “”;

          $db_conn->close();

          ?>

          I specified two fields (user and pass) in both tables, asking for the user to confirm his username (usuario) and pass (senha) while registering a new event.Then I’m trying to compare both on SELECT query.

          But if I enter the user_panel.php with another username, this one is able to see the registered event of the first user.

          Reply

          1. $sql = “SELECT cad_eventos.*, login.usuario
            FROM cad_eventos INNER JOIN login
            ON cad_eventos.usuario = login.usuario”;

  71. Reply

  72. Hi! I’m having a problem, i found out that after you successfully log in and you are in the homepage, when you click the “BACK” button, it goes back to the login page, which is not very wise. it should still remain in the homepage. please help

    Reply

  73. Hi first of all thank you for this tutorial. i am using this script it was working in local server, but not working while i am put it into main server. please help me

    Reply

  74. excellent tutorial man! thank you so much

    Reply

  75. thier some error. i cant access the index.php

    Reply

  76. thanks for this.

    Reply

  77. I’ll right away take hold of your rss as I can not find your
    email subscription hyperlink or newsletter service.
    Do you have any? Kindly permit me recognise so that I may just subscribe.
    Thanks.

    Reply

    1. Hello TBDP,

      You can follow up this link to get in touch with all latest blog posts.

      https://www.formget.com/blog/

      Hope you will be benefited with that.

      Thanks & Regards,
      FormGet.com

      Reply

  78. thanks

    Reply

  79. hi sir can you please tell me php how to create login and signup use to MYSQL

    Reply

  80. Hi… this tutorial is awsome it wroks perfectly…. but i got a question..

    if i want to logging as admin i want to show me admin form, but if i was a user logging it shows me the same admin form

    ¿How do i redirect to my userpage?

    Reply

    1. I think you should set up permissions for various user groups in your database

      Reply

  81. Thank you for the amazing code. But can you help me with one question.
    can one login page fetch data from multiple tables. If yes.can you please help me with the code.

    Reply

  82. Thanks for uploading such a nice link.

    I have done all the things,, all things are working properly and i logged in correctly,,,, when I logged out then i go back to login screen,,, this means that all sessions are destroyed .

    But when i press browser’s back button then i go back to the user profile screen,,where i did not get user’s name otherwise all same.., its mean session does not destroyed correctly.??

    Please clarify this,,,, I did this in your demo,,,that was working nice,,no such issue.
    Please reply me by my email asap.
    thanks

    Reply

  83. Hello. Where do I configure the database login username, password, host etc? I have webhost, so localhost won’t work. Thanks for answers 🙂

    Reply

  84. thanks its working..and i have done it through your helping.

    Reply

  85. great help by you to me , it means alot to me. thanks again.
    keep posted.

    Reply

  86. thanks you make my project more easier.
    fekadu(africa,Ethiopia)!

    Reply

  87. i have try your ‘lesson’ above

    but in my cpanel i try to configure
    where and when i must put the ‘page.html’ in case if

    example:
    – pageloginsuccess.html if login success, and
    – pageerrorlogin.html if login error

    i mean the comment of redirecting
    thx before

    Reply

  88. Hey

    Does the source code provided above allow me to create a functional php mysql login database?

    i would pay for the download but im just a student and im doing this for my computer science work.

    could you give any advice on how to create a safe php mysql database with log in a register that will be very difficult to hack in the hour i will be presenting the work?

    Reply

  89. Hi

    i thanks! That helps me a lot!
    Is it possible to create a cookie?
    I want to save the log in page as “apple web app” on my screen. and i don’t want to write everytime the password…
    best greats from germany
    Lukas

    Reply

  90. Hello .
    it is a good tutorial .. 🙂
    By the way , I wanna ask if this coding will make the username appear at every pages of our website ?

    Reply

  91. i fixed this now,had to make a single modification. Now this is my problem.

    Fatal error: Call to undefined function mysql_connect() in C:\ApacheServer\htdocs\login.php on line 14

    Reply

  92. Hi, I followed the code and made all the necessary changes but when I log in, the next page is blank. The url reads …/login.php but there is no action taken, it doesn’t take me to page profile.php.
    And also, I do not understand how the below code comes into play in session.php in the msql query statement
    username=’$user_check'”

    Reply

    1. Realized my mistake 🙂

      Reply

  93. I have completed your script and it works fine, but when I log out and then press the back button I get error message saying that the input from the login screen is not recognised. Please Help.

    Reply

  94. Could someone please explain the need for the session.php file?

    Reply

    1. For storing Session Variables, making sure the user is logged in. etc.

      Reply

  95. Thanks a lot dude….. it really helped me. thank you..!!!!

    Reply

  96. I search to google and then I know where’s the error of it.. It is lacking and here is the complete code. Thank you again 🙂 God Bless

    logout.php

    Reply

  97. thanks. 🙂

    Reply

  98. thank you.very well work done at here.it’s simple to understand.

    Reply

  99. Thank you very much very helpfullll 🙂

    Reply

  100. I get the error: This webpage has a redirect loop
    details say: Error code: ERR_TOO_MANY_REDIRECTS

    idk, I just copied and pasted the code. Im using the lastest version of XAMPP

    Reply

  101. I just wanted to say a big big thank you for your code, it has helped me greatly. Thanks for sharing!
    Kind regards
    Gaza

    Reply

    1. Reply

      1. hi admin can you help me i copy ur code and i try but after i submit the data

        this is the result,,

        //This webpage has a redirect loop)

        i dont have idea on how to solve this problem anyone can help me

        Reply

        1. maybe you didnt start the xampp or the localhost

          Reply

  102. it doesn’t work..

    Reply

    1. //This webpage has a redirect loop// —whats the meaning of this?

      Reply

      1. Make sure you have the right information in the session.php file

        Reply

  103. this code has been very helpfull. Can I get the full download

    Reply

  104. admin,

    i got this error page
    The webpage at http://localhost/php/package/index.php has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.

    Reply

  105. any different website is there like w3shcools

    Reply

  106. Hi,
    just i create a registration form and user login by using formget ,i would like ask how can get register username and password is used to login please help me dude

    Reply

  107. Hola,

    Al ejecutar el programa tengo el siguiente error: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\registration.php on line 84

    Reply

    1. Reply

  108. i currently try your tutorial. .as i finished it. .it is not really secured. .coz once you had loged in. you can back to the main or to the index without using log out form. therefore, others can used your account without registering.

    Reply

  109. ?php
    session_start();
    if(!isset($_SESSION[‘id’]))
    {
    header(‘location: login.php’);
    }
    else
    {
    ?> //it is using for in your header in page //login is page enter your page name here

    // it is using on end of

    Reply

  110. This is very good example

    Reply

  111. very helpful example of php session thank you…

    Reply

  112. hot do i link this together?

    Reply

  113. nice!!!!!!

    Reply

  114. I am very happy of that demo because for learn php very our help it

    Reply

  115. thanks

    Reply

  116. how to create customer profile with login session??? the login session i use your login ……… plzzz i needed …..
    plzzz reply my question……

    Reply

  117. Your tutorial is very helpfull..learnt alot from it

    Reply

  118. So about PHP 5.6 mysql_ …… is deprecated, so I change every mysql_ …. with mysqli, make table in database and connect successfully, but when I type my username and password it says: “Username or Password is invalid”. So I think in this code have some mistake, but I can’t understand what is..:

    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysqli_real_escape_string($username);
    $password = mysqli_real_escape_string($password);
    // Selecting Database
    $db = mysqli_select_db(“company”, $connection);
    // SQL query to fetch information of registerd users and finds user match.
    $query = mysqli_query(“select * from login where password=’$password’ AND username=’$username'”, $connection);
    $rows = mysqli_num_rows($query);
    if ($rows == 1) {
    $_SESSION[‘login_user’]=$username; // Initializing Session
    header(“location: profile.php”); // Redirecting To Other Page
    } else {
    $error = “Username or Password is invalid”;
    }

    Reply

    1. Reply

  119. very very useful codes it gives accurate results..

    Reply

  120. nice post !!!!!!!!!!!!!!!!!!!!

    Reply

  121. Hi………
    What is the use of session? And difference between session and normal login code?

    Reply

  122. Great Job Sir! Code really helped and worked smoothly.
    But their is one problem i’m facing. The output isn’t coming the same as above.

    In style.css file, “@import http://fonts.googleapis.com/css?family=Raleway;” is not able to import that googleapis’ code and the text in all headings and labels is appearing in ‘TIMES NEW ROMAN’ . Can’t figure it out the the error. Performed a number of changes with other fonts also but didn’t worked.

    Please Help!

    Reply

  123. I would strongly recommend converting this to PDO (php 5.1) so you don’t have to worry about escaping anything out and the code is cleaner. bindParam should sanitize your data. I would also recommend using password_hash (php 5.5) and/or password_verify (php.5.5) because you should *never* store passwords in plain text. Always hash them.

    By doing both of these your code is cleaner (e.g. your db connection info is stored in a singular place, making future changes trivial), uses the latest security, and doesn’t care which database back end you use.

    With the help of your code I was able to make a SQLite version which uses PDO and password_hash (which, with PDO, doesn’t really mater what back-end you use with the exception of the create script I use). Here is some of it and I’m sure, with your skills, you can quickly slap the rest together as it’s pretty obvious.

    Regardless, thanks for putting this page together!

    /****** LOGIN.PHP CODE HERE ******/

    require_once(‘config.php’);
    session_start();
    $error=”;

    if (isset($_POST[‘submit’])) {

    if (empty($_POST[‘username’]) || empty($_POST[‘password’])) {
    $error = “Username or Password is invalid”;
    }
    else {
    $username=$_POST[‘username’];
    $password=$_POST[‘password’];
    $db = new PDO($db_login);

    $statement = $db->prepare(“SELECT * FROM Login WHERE Username = :username”);
    $statement->bindParam(‘:username’, $username);
    $statement->execute();

    $row = $statement->fetchObject();

    if (!empty($row)){
    $hash = $row->Password;

    $match = password_verify($password, $hash);

    if($match == false) {
    echo “Username / Password invalid.”;
    } else {
    $_SESSION[‘login_user’] = $username;
    header(“location: profile.php”);
    }
    }

    $row = null;
    $statement = null;
    $db = null;
    }
    }

    /****** SESSION.PHP CODE HERE ******/

    require_once(‘config.php’);

    $db = new PDO($db_login);
    session_start();

    $user_check=$_SESSION[‘login_user’];

    $statement = $db->prepare(“SELECT Username FROM Login WHERE Username = :username”);
    $statement->bindParam(‘:username’, $user_check);
    $statement->execute();
    $row = $statement->fetchObject();

    $login_session = $row->Username;

    // Close everything, jut to be sure.
    $row = null;
    $statement = null;
    $db = null;

    if(!isset($login_session)) {
    header(‘Location: login.php’);
    }

    /****** CONFIG.PHP CODE HERE ******/

    date_default_timezone_set(‘America/Chicago’); // US – Central Time Zone

    $db_login = “sqlite:Inventory.sqlite”; // Connection string here. If you change this, make sure to adjust the create.sql to match the appropriate schema.

    Reply

    1. Thanks a lot for sharing your code.

      Regards
      Neeraj
      FormGet Team

      Reply

  124. Thanks a lot you made my day .. 😀

    Reply

  125. Nice blog very helpful It made Login/Logout form easy to deal with sessions in PHP

    Reply

  126. Can u do the code in PDO form please?? Everything works fine in this code but i want it PDO format.It would be great if you provide the link for PDO format!!
    Thank u

    Reply

  127. All fine and good but you really shouldn’t promote the use of the old mysql extension. It is more than ten years old and PHP programmers need to learn how to use PDO or mysqli and prepared statements.

    Reply

    1. Would you like to submit a tutorial based mysqli for the users ?

      Reply

  128. Thank you for this code. My professor didn’t teach us how to use Session and many more and now he want us to create a simple website to Create a simple Dynamic website.

    Thanks again.!

    Reply

  129. Thank you so much

    Reply

  130. Very helpful lesson for new php learner.

    Reply

  131. all things are well come.

    Reply

  132. Thank you very much for the reputable document above. I have one more question How to combine the above codes to appear in only one php file?

    Reply

  133. I am working in php , and your publishing is very userful to me and its too clearly i like this thank you

    Reply

  134. Hi,

    If I try to visit a page which is protected by the session, I get this in the error_log:

    PHP Notice: Undefined index: login_user in

    Obviously it happens because ‘login_user’ isn’t defined because they’re aren’t logged in but is there a way to stop that?

    Thanks

    Reply

    1. if(!isset($_SESSION[‘login_user’])) {
      header(“Location: index.php”);
      exit;
      }

      Reply

  135. For me i need a complete/ comprehensive login and logout system (codes) that will help me to develop my own thing i.e system as am still a young php developer.

    Reply

  136. Hi, I’m wondering how do I retrieve & display data from database using this session? Thanks.

    Reply

  137. hi..
    thanks for sharing the code for login page.. i follow your coding method and successfully login. but i have a problem when i click on log out. my log out does not function, it display a blank page, then i try it again, it still the current user name login. how to make it function?

    Reply

  138. Simply awesome.

    Reply

  139. sir ,
    i copied all the codes that u r given in this blog i created db in wamp server also but while running the programs(all) iam getting the code asusual as i copied can u pls give me the suggestion to run this ,iam new learner of php in online

    Reply

  140. Awesome description about creating session and using session variables in PHP. Simple and Easy to Understand.

    Reply

    1. can u pls tel me how to execute this program iam new learner i copied all the code and created db in wamp server and imported login.php but iam not getting output ,the total code which i copied is executing while running pls help me to execute

      Reply

  141. Thank you very much
    Danke schönnnnnnnnnnnnnnn. German
    Faliminderit shummmmmmmmm. Albanian

    Reply

  142. sir, please send full project in php?ect name i
    project name is Hotel management System

    Reply

  143. Very very very gooooodddd website….This is very helpful for me…

    Reply

  144. Very Nice system, it’s good code and security – it’s great system.
    good luck man, you are a good man 🙂

    Reply

  145. Hi i saw your coding it can be work login or logout ……Thank u so much……

    Reply

  146. I get error at index.php line 4. It says “Parse error: syntax error, unexpected ‘if'”.
    How to fix it? Thanks

    Reply

  147. Awesome.
    Very Simple and straight forward.
    Keep it up this work.
    Thanks.

    Reply

  148. good script, thanks

    Reply

  149. Anyone knows why i get autofilled username and password with root.. i have disabled autofill in my browser

    Reply

    1. Reply

  150. Good tutorial. However, I get a redirect loop error after i finished doing all steps. Can you please show me how to rectify this.

    Thanks.

    Reply

  151. Hello mates, its great piece of writing concerning teachingand entirely
    defined, keep it up all the time.

    Reply

  152. Hey admin it works fine, good job.
    But how do i store other variables like email, rank, and so on?

    Reply

    1. Nevermind i figured it out change session.php to

      Then use this sql code

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

      — Host: 127.0.0.1
      — Generation Time: Apr 25, 2015 at 07:51 PM
      — Server version: 5.6.21
      — PHP Version: 5.5.19

      SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
      SET time_zone = “+00:00″;

      /*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
      /*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
      /*!40101 SET @[email protected]@COLLATION_CONNECTION */;
      /*!40101 SET NAMES utf8 */;


      — Database: `company`

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


      — Table structure for table `login`

      CREATE TABLE IF NOT EXISTS `login` (
      `id` int(10) NOT NULL,
      `username` varchar(255) NOT NULL,
      `password` varchar(255) NOT NULL,
      `email` varchar(255) NOT NULL,
      `rank` varchar(255) NOT NULL
      ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;


      — Dumping data for table `login`

      INSERT INTO `login` (`id`, `username`, `password`, `email`, `rank`) VALUES
      (1, ‘SaintNic’, ‘Silver98’, ”, ‘Administrator’);


      — Indexes for dumped tables


      — Indexes for table `login`

      ALTER TABLE `login`
      ADD PRIMARY KEY (`id`);


      — AUTO_INCREMENT for dumped tables


      — AUTO_INCREMENT for table `login`

      ALTER TABLE `login`
      MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
      /*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
      /*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
      /*!40101 SET [email protected]_COLLATION_CONNECTION */;

      Reply

    2. $connection = mysql_connect(“localhost”, “root”, “”);
      $db = mysql_select_db(“test”, $connection);
      session_start();
      $user_check=$_SESSION[‘login_user’];
      $ses_sql=mysql_query(“select username from login where username=’$user_check'”, $connection);
      $user_data_sql=mysql_query(“select username, password, email, rank from login where username=’$user_check'”, $connection);
      $row = mysql_fetch_assoc($ses_sql);
      $output_data = mysql_fetch_assoc($user_data_sql);
      $login_session =$row[‘username’];
      $login_session_password =$output_data[‘password’];
      $login_session_email =$output_data[’email’];
      $login_session_rank =$output_data[‘rank’];
      if(!isset($login_session)){
      mysql_close($connection);
      header(‘Location: ./index’);
      }

      Reply

  153. thanks, your program is very good!

    Reply

    1. You can also add an ht access folder

      Make a new folder called “.htaccess”

      And put this code in it

      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule ^([^\.]+)$ $1.php [NC,L]

      Or if you want to add a trailing slash at the end use this code

      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteRule ^([^/]+)/$ $1.php
      RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
      RewriteRule (.*)$ /$1/ [R=301,L]

      Now you don’t have to put the .php at the end of you files 🙂

      Reply

  154. Hi ,

    This tuturial is very nice , just i show and currently i am studying your tutorial.

    Reply

  155. The example is great and works perfectly, would it be possible to get a tutorial from this to allow users of different access levels different restrictions when logging in such as admin functions and user functions?

    Reply

    1. Yea it’s very simple use the my sql table above in my previous comment

      And change session.php to

      $connection = mysql_connect(“localhost”, “root”, “”);
      $db = mysql_select_db(“company”, $connection);
      session_start();
      $user_check=$_SESSION[‘login_user’];
      $ses_sql=mysql_query(“select username from login where username=’$user_check’”, $connection);
      $user_data_sql=mysql_query(“select username, password, email, rank from login where username=’$user_check’”, $connection);
      $row = mysql_fetch_assoc($ses_sql);
      $output_data = mysql_fetch_assoc($user_data_sql);
      $login_session =$row[‘username’];
      $login_session_password =$output_data[‘password’];
      $login_session_email =$output_data[’email’];
      $login_session_rank =$output_data[‘rank’];
      if(!isset($login_session)){
      mysql_close($connection);
      header(‘Location: ./index’);
      }

      Then in your database create an account then put rank as 1 for user and 9 for administrative

      Restrict pages only to administer put this code at the top make sure you include session.php first

      if ($login_session_rank == “9”) {
      } else {
      header(“location: ./restricted.php”)
      exit;
      }

      Then create a php file called restricted and make it say you have no access to view this page

      I’ll use (?php, ?) As starting and ending brackets

      what about if your an admin and you want stuff to be show for admins but not for users on a certain page

      (?php
      if ($login_session_rank == “9”) {
      ?)
      Page content admin can see
      (?php
      }
      ?)

      But that’s how I did the access levels and you can add more like moderator and etc.

      Reply

      1. i cant seem to get the example working it is saying that i have the following error

        “Parse error: syntax error, unexpected T_STRING in /home/atreddenick/public_html/login_example/session.php on line 11”

        and this is what i have on that line

        “$user_data_sql=mysql_query(“select username, password, rank, from login where username=’$user_check’”, $connection);”

        i have taken out the email part as it is not necessary for my example but i cant work out where i have gone wrong.

        Any help would be great.

        Thanks

        Reply

        1. What does your sql code look like ??

          sometimes it’s the sql code

          ilike for example if your sql looks like this for the login table

          CREATE TABLE IF NOT EXISTS `login` (
          `id` int(10) NOT NULL,
          `username` varchar(255) NOT NULL,
          `password` varchar(255) NOT NULL,
          `email` varchar(255) NOT NULL,
          `rank` varchar(255) NOT NULL
          ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

          and you do

          “select username, password, rank”

          you will get an error
          because you can skip email so I would either delete the email field or put rank before email

          If you want I can email you the script, I have made admin levels, remember me, and other cool functions, I even managed to create a mysqli, and a PDO Connection so if you want me to send the script to you email me at “[email protected]” put PHPLoginHelp as subject and ill email you back as soon as I can 🙂

          Reply

        2. What does your whole session.php code look like the whole file content ?

          Reply

  156. it is good tutorial..i am not a average student of php below average………but i can easily to understand the tutorial………its more help me

    Reply

  157. it is not clear once wamp server is loaded on my computer, and your directory ‘php_login_form’ is put in root director www. of wamp localhost…what to do next?

    I mean how to connect with my own external web server and pass or create database for login from wamp server on my computer?
    thanks
    Damir

    Reply

  158. Can you help me. How to make login page when the user have different database. i have admin table and i have owner table.

    Reply

  159. Hi admin,
    I am fed up with error…please may u help me out.
    No matter what i type in user name and password fields, i am always getting Invalid login. My database has 3 fields (id, username, password)

    Reply

  160. Hey Neeraj,

    Thanks a ton for the pseudo code. This saved my time.

    Reply

  161. Thanks a lot guys – easy, clear and clean!

    Although, used prepared statements. E.g. for login.php (for anyone wondering):

    […]

    $mysql_hostname = ‘localhost’;
    $mysql_dbname = ‘db_name’;
    $mysql_username = ‘root’;
    $mysql_password = ‘123’;

    $connection = new PDO(“mysql:host=$mysql_hostname;dbname=$mysql_dbname”, $mysql_username, $mysql_password);

    $conn_statement = $connection->prepare(“SELECT username, password FROM account WHERE username = :username AND password = :password”);

    $conn_statement->execute(array(‘:username’ => $username, ‘:password’ => $password));

    $affected_rows = $conn_statement->rowCount();
    if ($affected_rows == 1) {
    $_SESSION[‘account_session’] = $username;
    header(“location: ./template/account.php”);
    }
    else {
    $error = “Given information is invalid!”;
    }
    $connection = null; //closing connection

    Reply

  162. Thank you very macho. It’s nice work

    Reply

  163. Hello,

    I got a problem that it doesn’t want to execute the header command.

    it just ignores it..

    I have read some things but it’s still not really clear what i have to do..

    Can u help me ? thanks !

    Reply

    1. i added this

      header( “refresh:2;profile.php” );
      echo ‘You’ll be redirected in about 2 secs. If not, click here.’;

      when i click the link then it goes to profile.php, but then it doesn’t show the name of the user.

      Reply

      1. Hello Pieter,

        Thank you so much for reading the post.

        I have checked it at my end and found it to be working fine.

        you should to add header( “refresh:2;profile.php” ); in both login and index file.

        Let me know if any doubt persists.

        Regards,
        FormGet Team.

        Reply

  164. how could i put these codes in www director of wamp server p/s help me am new for web development..

    Reply

    1. Hello Yirgalem Mekuria.

      First, create a folder name loginwithphp or any name and inside loginwithphp, create all files which are mentioned above, after
      if you are using wamp then copy here
      C:/wamp/www
      for xamp
      C:/xampp/htdocs

      Do the following steps for database setup
      1) Go to http://localhost/phpmyadmin
      2) Then create new database “company”
      3) Create a table name, login with above mentioned attributes and insert dummy data on it

      Now open your browser and run index.php
      http://localhost/login-form-php_download/index.php

      Let me know if any doubt persists.

      Regards,
      FormGet Team.

      Reply

  165. Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\Hosting\5477578\html\vijayadasaru.net\test\login.php on line 24 this is the error message iam getting

    Reply

    1. Help?
      Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in
      public_html/Home/login.php on line 24

      Reply

  166. I’m not getting any emails and an error when resetting password:

    Undefined variable: subject in C:xampphtdocsdemo2php_login_formpassword_reset.php on line 68

    As instructed I have updated link to http://www.songuide.com in all corresponding files.

    Reply

  167. Uff…! Thank You sir for sharing this.

    Reply

  168. thanks.
    works great.
    🙂 😀

    Reply

    1. Just a warning, this is easily one of the most dangerous ways to handle password storage, and by using this technique as-is, you are putting the passwords of all of your users at risk.

      Reply

  169. It is worth nothing that this is an incredibly insecure way to handle logins. You should NEVER store a password in a database. The correct way to do this is by using a cryptographic hash to store the salted password in the database. Thus, if your database is compromised, you will not leak passwords for all of your users as so many companies have done recently. This is especially important as users may reuse these passwords on much more important and secure sites.

    The correct way is:
    Accept user password
    Generate random salt
    Hash password + salt
    Store this hash and salt

    Now, when someone attempts a login, you would take what they supply for their password, append the stored salt, hash it, and compare that to the stored hash in your database.

    To anyone writing a tutorial, I implore you to please stop spreading dangerous and irresponsible practices. You have a duty to your users to have at least a modicum of understanding of security for their sake.

    Reply

    1. This is true, and to add to the alarm, it’s using mysql instead of mysqli or PDO. No tutorial using mysql instead of the latter should be really taken seriously at this point in the game since it’s been proven vulnerable and is now deprecated.

      Reply

  170. very awesome code

    Reply

  171. Hey, great page and worked first time and was very easy to understand.
    I am guessing that if I include the code

    Reply

  172. Hey, great page and worked first time and was very easy to understand.
    I am guessing that if I include the code

    then it will make sure that the user is logged in and allowed to see it?

    Reply

  173. Its a good and clean code thanks very much

    Reply

  174. it is help full tutorial so i want to say tank you
    but can you add something about how to check login password with registration password

    Reply

  175. Hello every one. Nice code admin but I’m having a problem with the login section it keeps bringing the error message and the database help me on auto increment

    Reply

  176. Very Nice 🙂

    Reply

  177. plz help.. how can i get the SQL.file

    Reply

  178. Hi,
    admin i saw your tutorial demo and i liked it but its difficult form me to understand how do you prevent your page from going back or could you make an video tutorial please.
    Thank you

    Reply

  179. thank you very much

    Reply

  180. What is the purpose of “id” in:

    UserName :

    Password :

    is it really required to have that “id”?
    what is the difference of “id” in “name”?

    Reply

  181. Thanks though I have my own login form with database still I really like this one simple and very understandable… Thank you so much

    Great Job ! 🙂

    Reply

  182. Thanks, New knowledge for me

    Reply

  183. Frnz how can we link website code in cpanel to domain name.

    Reply

  184. why you have used the following code at the very starting of index.php ??

    Reply

  185. Hi,

    Wonderful tutorial and thanks for your sharing.

    I just have a question that: how to record the login time while successful log-in?
    I tried to record the login time to another table (but in same database) after success log in. However did not work. Can anyone help me?

    Thank you.

    Rebecca

    Reply

  186. thank you so much

    Reply

  187. Warning:session_start(): Cannot send session cookie and cache limiter – header already sent (output started at C:\xammpplite\htdocs\project\login.php on line 2
    “” on line 24
    “” index.php on line 5

    Reply

  188. Hi Admin, thanks for the codes though I had a bit of a problem.
    I copied all those codes, even made the database. Everything works perfectly.
    Well not everything, when I press the logout button, which redirects to logout.php where the session gets cut off, instead of redirecting to index.php it just stays there. A white page, nothing. Nothing happens. Any ideas what caused it?
    I need it for a project. Thank you so much sir

    Reply

  189. what is this thing i do not know and i have never use php before in my life and this language is great and easy and i will continue to lerning and i hope one day i will be master of thise language…

    Reply

  190. Thanks a lot…… 🙂 i want this code………….

    Reply

  191. Great code and worked fine in WAMP but when I uploaded it to my website host I encountered the same problem that several people on this page have already had: –

    Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /home1/bespokew/public_html/admin/profile.php:2) in /home1/bespokew/public_html/admin/session.php on line 12

    I followed your advise of putting ‘@ob_start();’ before ‘session_start();’ but the same error message keeps appearing. Please help.

    Reply

  192. I make HTML web on my computer desktop after that i installed xampp and xampp -> htdocs folder i make login php so, my question is that do i need to make index.php on it or not if so how about html that i created on desktop.that index.html also i have to move on xampp -> htdocs folder

    Reply

  193. Hey ya, i’m very glad to read your tutorial. And i’m it’s very helpfull for me :). Thanks for everyone doing this job, and sorry for my bad english :).

    Reply

  194. I am working on your example and i get this error.. i can’t find solution please please help….

    “mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:wampwwwaddscloudsession.php” on line 13

    Reply

    1. Hello,

      Such error occurs usually when the mysqli_query hasn’t run properly.
      Check whether your query is executed properly or does it contains anything or not. The problem may be with the connection, query or it may be with the tables.

      So, make sure that your query must contain the same table name that you have created in your database. Also, check that the query contains the results.

      Reply

  195. Hello, i am having a problem where it opens the “500 Internal Server Error” upon sign in, could that be a result of changing the name of the table from the sql that you have above, if so, how would i fix this problem, thanks

    Reply

    1. Hi,

      Use the same database name, table name and column name in query that you have created at your end. It would resolve your issue.

      Reply

      1. hi i like ur login pgm. its very nice. i have a little problem with mine.
        i added more fields to database tables and i want it displayed. pls hw do i do it. i have tried all method but it doesn’t read the entire row iinformation to display in profile.php

        Reply

  196. i m having trouble with connecting html website with ,my spl
    please tell me any ways so that i can connect them

    Reply

  197. In this way the session connection it’s very simple!
    Grazie tante from Italy

    Reply

  198. thanks for the tutorial. pls can you help me i want to display full user info from my db row when user logs in. i added more fields to tthe table

    Reply

  199. Thanks for your loginpage

    Reply

  200. It’s real helpful to me

    Reply

  201. Hello all, here every one is sharing these know-how, therefore it’s nice to read this webpage,
    and I used to visit this website all the time.

    Reply

  202. Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/ezbz_4/login.php on line 22

    Reply

  203. This post is awesome. Really very helpful. (y)

    Reply

  204. How to check with session which user is logged in … ? if i want to access page i can’t … like if i am logged in as user1 and i hvae my view of my profile and someone else logged as user2 want to see my profile and he type in url .php?u=$username and my username which show my profil info is user1 … how to use session to see am i visiting that page or somebody else.. so if its me i get page with everything and if it is somebody else he gets page with some of my info?

    Reply

  205. thank you it is very informative 🙂
    keep up

    Reply

  206. Works great, thank you to share!
    Also, the css file produces a clean, nice, and easy interface.

    Reply

  207. Also, to make it responsive for mobile, don’t forget to add the below meta inside your head tags:
    <meta name="viewport" content="width=device-width, initial-scale=1"

    Reply

  208. Am planning to prepare one project and need some help and suggestions.

    Reply

  209. Hi,
    I have updated the terms for Mysqli, but no matter what i try to login with i got Username and Password is invalid as the result, even though it is corrected to the corrected table within the database. any help would be great.

    Reply

  210. thank you guys it help a lot .

    Reply

  211. Why in the session.php file do you check again if the user exists in the database? It’s a security problem or it’s just to retrieve user datas?
    Thank you for your help, I hope you still answer to questions on this post 😛

    Reply

  212. Hi
    Im trying to get the username of the logged in user displayed, i have implemented sessions but to no avail. Once the user logs in at first it displays the message you are logged in as “Eddy Kay” for instance, but once you click another link the username vanishes. Could you tell me what I am doing wrong please.

    Here is the code below.
    User_User.class.php
    class User_User {
    public function __construct(){
    //start a session
    session_start();

    }

    public function isLoggedIn(){
    $sessionIsSet = isset( $_SESSION[‘username’]);

    if ( $sessionIsSet ) {

    $out = $_SESSION[‘username’];
    } else {
    $out = false;
    }
    return $out;
    }

    public function login () {
    //set session variable [‘logged_in’] to true
    $_SESSION[‘username’] = true;
    }

    public function logout () {
    //set session variable [‘logged_in’] to false
    $_SESSION[‘username’] = false;
    }

    }

    User_Table.class.php
    checkEmail( $email );
    $this->checkUsername($username);
    //encrypt password with MD5
    $sql = “INSERT INTO users (email, firstname, lastname, username, password)
    VALUES(?, ?, ?, ?, MD5(?))”;
    $data= array( $email, $firstname, $lastname, $username, $password );
    $this->makeStatement( $sql, $data );
    }

    private function checkEmail ($email) {
    $sql = “SELECT email FROM users WHERE email = ?”;
    $data = array( $email );
    $this->makeStatement( $sql, $data );
    $statement = $this->makeStatement( $sql, $data );
    //if a user with that e-mail is found in database
    if ( $statement->rowCount() === 1 ) {
    //throw an exception > do NOT create new admin user
    $e = new Exception(“Error: ‘$email’ already used!”);
    throw $e;
    }
    }
    private function checkUsername ($username) {
    $sql = “SELECT username FROM users WHERE username = ?”;
    $data = array( $username );
    $this->makeStatement( $sql, $data );
    $statement = $this->makeStatement( $sql, $data );
    //if a user with that e-mail is found in database
    if ( $statement->rowCount() === 1 ) {
    //throw an exception > do NOT create new admin user
    $e = new Exception(“Error: ‘$username’ already used!”);
    throw $e;
    }
    }

    public function checkCredentials ( $username, $password ){
    $sql = “SELECT username FROM users
    WHERE username = ? AND password = MD5(?)”;
    $data = array($username, $password);
    $statement = $this->makeStatement( $sql, $data );
    if ( $statement->rowCount() === 1 ) {
    $out = true;
    } else {
    $loginProblem = new Exception( “Username/Password incorrect” );
    throw $loginProblem;
    }
    return $out;
    }
    public function getUserName($username)
    {
    $sql = “SELECT username FROM users WHERE username = ? “;
    $data = array($username);
    $statement = $this->makeStatement($sql, $data);

    return $statement;
    }

    }
    ?>

    login.php

    checkCredentials( $username, $password );
    $userTable->getUserName($username);
    $user->login();

    } catch ( Exception $e ) {
    //login failed
    }
    //end of code changes

    }

    $loggingOut = isset ( $_POST[‘logout’] );
    if ( $loggingOut ){
    $user->logout();

    }

    if($user->isLoggedIn())
    {

    $view = include_once “views/logout-form-html.php”;
    }
    else
    {
    $view = include_once “views/login-form-html.php”;
    }

    return $view;
    ?>

    login-form-html.php
    <?php
    return "
    Login to access restricted area
    Username
    Password

    “;
    ?>

    logout-form-html.php
    <?php
    if (isset($username) === false )
    {
    $username = "";
    }

    return "
    logged in as $username

    “;

    ?>

    Thank you.

    Reply

  213. Hello
    Why you call two time redirect on profile.php header(“location: profile.php”); ?
    One time in login.php, and second in index.php?

    Regards
    Alexander

    Reply

  214. i am studing how to make login form in php using session but i am getting an error stating ”
    Object not found!

    The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

    If you think this is a server error, please contact the webmaster.
    Error 404
    localhost
    04-12-2015 14:09:52
    Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1

    please advice..

    Reply

  215. Hi? I don’t think it might helped me out but frankly it gives me an idea. Thanks.

    Reply

  216. whenever i refer to my profile.page first it wont take me to index.page.. i dont know why its doing this, but this peace of code never works i think in any case.. any help please.

    Reply

  217. On loading index.php, browser displays that ” This web page has a redirect loop “, so how to overcome this problem ?

    Reply

  218. love you nice code thank you so much but need some changes to mysqli

    Reply

  219. Quality articles is the crucial to be a focus for the users
    to visit the site, that’s what this web site is providing.

    Reply

  220. I was recommended this website by my cousin. I’m now not sure whether or not this put up is
    written via him as no one else realize such distinct approximately my problem.
    You are incredible! Thank you!

    Reply

  221. Thank you so much.. I wasted days to find how to create a login form. This worked. (y)
    Keep up the good work!

    Reply

  222. Yes it works

    Reply

  223. helpful than i read b4…..thanks!

    Reply

  224. Nice program and self explanatory…All the best

    Reply

  225. This post will assist the internet people for building up new blog or even a weblog from
    start to end.

    Reply

  226. Very nice code.it usefull for mi . i like the way its describe.

    Reply

  227. What’s up, every time i used to check webpage posts here early in the daylight, because i love to gain knowledge of more and more.

    Reply

  228. Good blog post. I definitely appreciate this website. Keep writing!

    Reply

  229. Iblog often and I truely appreciate your content. Your article has really peaked my interest.

    I am going to bookmark your website and keep checking for new details about
    once a week. I opted in for your RSS feed
    too.

    Reply

  230. How can i start a new SESSION…
    Eg: on my table have “Access Level”, how can i call that as a SESSION..?

    Reply

  231. Sir sql is not working showing error

    Reply

  232. Thanks for sharinjg your thoughts on php
    login form. Regards

    Reply

  233. Making Same Please Help Me To Cpnfigure CSS And PHP Script On WAMP

    Reply

  234. Thanks a lot for this example, was of great use!

    Reply

  235. i need pdo login and registration form using php.

    Reply

  236. hey i just got this error
    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given

    Reply

  237. I am genuiinely grateful to the holder of this website who has hared this wonderful paragraph
    at at this place.

    Reply

  238. Your session does not work coorectly. If both auser are loged in, and when you refresh the page of the first user (which loged in), the datas of the last user will overide the datas of the first one.
    I programm a smiliar thing and have the same problem with the sessions.
    This happens, cause php create every time the same session for ervery user and not a individual session like in java ee.
    I hope you update your code with the correct solution.

    Best Regards Alex from Germany

    Reply

    1. thanks Alex for the update. i will like to share my source code with you so you can have a look at it. if you will have the time pls notify me on my mail. maybe we can collaborate, cos i’m building something else now. thanks in advance

      Reply

      1. It will make me happy to see more of your codes, maybe we can create codes together as example

        Greetings Alex

        Reply

  239. the code is really perfect. You made my day

    Reply

  240. Hi there all, here every onee is sharing these kinds of knowledge, so it’s pleasant to read this
    website, annd I used to pay a quick visit this website everyday.

    Reply

  241. Excelente aporte, me sirvió.

    ¡Muchas gracias!

    Reply

  242. Thank you for all the help you guys. i had struggled for a login page for 2years until tiday

    Reply

  243. You guys are awesome, help me a lot in making those Login forms. Keep It Up. Be Happy

    God Bless You

    Reply

  244. I’ve got error that says:

    Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given

    I tried to Google search for the possible solution to no avail. I tried to trap the error since it says that $query is a boolean:

    if (false === $query) {
    echo mysql_error();
    }

    The mysql_error is No database selected. Please help me and thanks a lot for the sample script.

    Reply

  245. Thank you very much it works perfectly

    Reply

  246. Thank You so much. This made my day. great job.

    Wish The best for u you.

    Reply

  247. This design is incredible! You obviously know how to keep a reader entertained.
    Between your wit and your videos, I was almost moved to start
    my own blog (well, almost…HaHa!) Wonderful job.

    I really loved what you had to say, and more than that, how you presented
    it. Too cool!

    Reply

  248. Thank you for this little tutorial I have Learned so Much in using session and stripslashes.

    Reply

  249. Please can anyone help???? I tried it but my session is not login in to my redirected page rather its returning me back to the login form….help me ou

    Reply

  250. CREATE DATABASE company;
    CREATE TABLE login(
    id int(10) NOT NULL AUTO_INCREMENT,
    username varchar(255) NOT NULL,
    password varchar(255) NOT NULL,
    PRIMARY KEY (id)
    )

    using it on xaamp my sql cmd
    but the error is “#1046 – No database selected”
    please help me figure it out

    Reply

  251. I have been checking out a few of your posts and i
    can claim nice stuff. I will make sure to bookmark your site.

    Reply

  252. What a fantastic page. Thank you for your help 🙂

    Reply

  253. hello thank you so much for this code!!! really big help!!

    Reply

  254. Its so amazing to have this kind of work and those kind of people who shares this ideas 😀 good job bruuu this is the only source code ive done in an ease 🙂

    Reply

  255. Thank you sir! This is really helpfull for me to realise what the session really is. Have a nice one!

    Reply

  256. Thanx a lot it help the young designers like us..

    Reply

  257. Work excellent

    Reply

  258. Perfect.
    Excellent tutorial.
    I thank you.
    There are many examples in NET, but yours was the only one that worked.
    Congratulations

    Reply

  259. thank you sir,for giving this understanding code to us.
    but iam getting the error is as below while redirecting to the login page to profile page
    This page isn’t working

    localhost redirected you too many times.
    Try clearing your cookies.
    ERR_TOO_MANY_REDIRECTS

    Reply

  260. Even though I did copy all codes correctly the login is not redirecting me to profile.php and shows blank screen.I did insert record in table login and used same while logging in.

    Reply

  261. whoah this blog is excellent i really like reading your posts.
    Keep up the great work! You understand, many
    persons are hunting round for this info, you can help them greatly.

    Reply

  262. hi
    admin
    thank you
    every thing is ok but
    username and password is invalid
    i mean i don’t know please help me
    i need username and password in login form

    thanks

    Reply

  263. I love the efforts you have put in this, thank you for all the great articles.

    Reply

  264. Quality content is the main to attract the viewers to visit the web page, that’s
    what this site is providing.

    Reply

  265. This article offers clear idea for the new users of blogging,
    that actually how to do blogging and site-building.

    Reply

  266. hello, i need your help.

    Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /Applications/XAMPP/xamppfiles/htdocs/login.php:14 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/index.php(2): include() #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 14

    Reply

Leave a Reply

How do I create a login session?

Table of Contents.
Step 1- Create a HTML PHP Login Form..
Step 2: Create a CSS Code for Website Design..
Step 3: Create a Database Table Using MySQL..
Step 4: Open a Connection to a MySQL Database..
Step 5 - Create a Logout Session..

How do I start a PHP session?

Start a PHP Session A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION.

How do I retrieve data from the database of a particular user after logging in PHP?

Retrieve or Fetch Data From Database in PHP.
SELECT column_name(s) FROM table_name..
$query = mysql_query("select * from tablename", $connection);.
$connection = mysql_connect("localhost", "root", "");.
$db = mysql_select_db("company", $connection);.
$query = mysql_query("select * from employee", $connection);.