How to Create Login and Logout Page with Session and Cookies in PHP

Language

In my previous tutorial, I've shown you How to Set up Cookie. This tutorial will give you an idea of how to use the stored cookie to login and I've added a "logout" function that destroys both session and cookie.

Creating our Database

First, we're going to create a database that contains our data.

  1. Open phpMyAdmin.
  2. Click databases, create a database and name it as "cookie".
  3. After creating a database, click the SQL and paste the below code. See image below for detailed instruction.
  1. CREATE TABLE `user` (
  2. `userid` INT(11) NOT NULL AUTO_INCREMENT,
  3. `username` VARCHAR(30) NOT NULL,
  4. `password` VARCHAR(30) NOT NULL,
  5. `fullname` VARCHAR(60) NOT NULL,
  6. PRIMARY KEY (`userid`)
  7. ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
cookie_login

Inserting Data into our Database

Next, we insert users into our database. This will be our reference when we log in.

  1. Click the database we created earlier.
  2. Click SQL and paste the code below.
  1. INSERT INTO `user` (`username`, `password`, `fullname`) VALUES
  2. ('neovic', 'devierte', 'neovic devierte'),
  3. ('lee', 'ann', 'lee ann');

Creating our Connection

The next step is to create a database connection and save it as "conn.php". This file will serve as our bridge between our form and our database. To create the file, open your HTML code editor and paste the code below after the tag.

  1. <?php
  2. $conn = mysqli_connect("localhost","root","","cookie");
  3.  
  4. // Check connection
  5. {
  6. echo "Failed to connect to MySQL: " . mysqli_connect_error();
  7. }
  8. ?>

Creating our Login Form

Next is to create our login form. In this form, I've added a code that if ever there's a cookie stored, it will show in the login inputs. To create the form, open your HTML code editor and paste the code below after the tag. We name this "index.php".
  1. <?php
  2. include('conn.php');
  3. ?>
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <title>Login Using Cookie with Logout</title>
  8. </head>
  9. <body>
  10. <h2>Login Form</h2>
  11. <form method="POST" action="login.php">
  12. <label>Username:</label> <input type="text" value="<?php if (isset($_COOKIE["user"])){echo $_COOKIE["user"];}?>" name="username">
  13. <label>Password:</label> <input type="password" value="<?php if (isset($_COOKIE["pass"])){echo $_COOKIE["pass"];}?>" name="password"><br><br>
  14. <input type="checkbox" name="remember" <?php if (isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){ echo "checked";}?>> Remember me <br><br>
  15. <input type="submit" value="Login" name="login">
  16. </form>
  17.  
  18. <span>
  19. <?php
  20. if (isset($_SESSION['message'])){
  21. echo $_SESSION['message'];
  22. }
  23. unset($_SESSION['message']);
  24. ?>
  25. </span>
  26. </body>
  27. </html>

Creating our Login Script

The next step is creating our login script. We name this script as "login.php".

  1. <?php
  2. if(isset($_POST['login'])){
  3.  
  4. include('conn.php');
  5.  
  6. $username=$_POST['username'];
  7. $password=$_POST['password'];
  8.  
  9. $query=mysqli_query($conn,"select * from `user` where username='$username' && password='$password'");
  10.  
  11. if (mysqli_num_rows($query) == 0){
  12. $_SESSION['message']="Login Failed. User not Found!";
  13. header('location:index.php');
  14. }
  15. else{
  16. $row=mysqli_fetch_array($query);
  17.  
  18. if (isset($_POST['remember'])){
  19. //set up cookie
  20. setcookie("user", $row['username'], time() + (86400 * 30));
  21. setcookie("pass", $row['password'], time() + (86400 * 30));
  22. }
  23.  
  24. $_SESSION['id']=$row['userid'];
  25. header('location:success.php');
  26. }
  27. }
  28. else{
  29. header('location:index.php');
  30. $_SESSION['message']="Please Login!";
  31. }
  32. ?>

Creating our Login Success Page

Next, we create a go-to page if login is successful. This page will show the user that login successfully. We name this page as "success.php". On this page, I've added the logout link to destroy both the session and cookie.

  1. <?php
  2.  
  3. if (!isset($_SESSION['id']) ||(trim ($_SESSION['id']) == '')) {
  4. header('index.php');
  5. exit();
  6. }
  7. include('conn.php');
  8. $query=mysqli_query($conn,"select * from user where userid='".$_SESSION['id']."'");
  9. $row=mysqli_fetch_assoc($query);
  10. ?>
  11. <!DOCTYPE html>
  12. <html>
  13. <head>
  14. <title>Setting Up Cookie on User Login</title>
  15. </head>
  16. <body>
  17. <h2>Login Success</h2>
  18. <?php echo $row['fullname']; ?>
  19. <br>
  20. <a href="logout.php">Logout</a>
  21. </body>
  22. </html>

Creating our Logout Script

Last is our logout script. This script destroys both our session and the cookie then redirects us back to our login page. We name the script as "logout.php".

  1. <?php
  2.  
  3. if (isset($_COOKIE["user"]) AND isset($_COOKIE["pass"])){
  4. setcookie("user", '', time() - (3600));
  5. setcookie("pass", '', time() - (3600));
  6. }
  7.  
  8. header('location:index.php');
  9.  
  10. ?>
DEMO

And that's the end of this tutorial. I hope this will help you and for your future projects. Feel free to download the working sample source code and test it.

Explore more on this website for tutorials and free source code.

Enjoy :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Submitted byRodante (not verified)on Sat, 10/07/2017 - 07:11

can i download? because important to make this project

Add new comment