Setting up Cookie upon Login using PHP/MySQLi

Submitted by: 
Language: 
Visitors have accessed this post 1489 times.

In my previous post, I created a Simple Login with Validation, so I've decided to create another tutorial to show how to set up cookie upon user login. But in this tutorial, I have created a simple login since the focus of this tutorial is to give you knowledge on how to set up cookie.

Cookies are small amount of data that has been stored in user's computer. This is used so that when the same computer access the website, some data are already available to use. Data usually saved by this method are id's.

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

Creating our Connection

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. To create the form, open your HTML code editor and paste the code below after the tag. We name this as "index.php".

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Setting Up Cookie on User Login</title>
  5. </head>
  6. <body>
  7. <h2>Login Form</h2>
  8. <form method="POST" action="login.php">
  9. <label>Username:</label> <input type="text" name="username">
  10. <label>Password:</label> <input type="password" name="password"><br><br>
  11. <input type="checkbox" name="remember"> Remember me <br><br>
  12. <input type="submit" value="Login" name="login">
  13. </form>
  14.  
  15. <span>
  16. <?php
  17. if (isset($_SESSION['message'])){
  18. echo $_SESSION['message'];
  19. }
  20. unset($_SESSION['message']);
  21. ?>
  22. </span>
  23. </body>
  24. </html>

Creating our Login Script

Next step is creating our login script. We name this script as "login.php". If the user checks the "Remember me" checkbox, it will store user information via cookie.

  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. No user 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. $name_cookie = "user";
  21. $value_cookie = $row['userid'];
  22. setcookie($name_cookie, $value_cookie, time() + (86400 * 30)); // cookie will expire in a month, 86400 = 1 day
  23. }
  24.  
  25. $_SESSION['id']=$row['userid'];
  26. header('location:success.php');
  27. }
  28. }
  29. else{
  30. header('location:index.php');
  31. $_SESSION['message']="Please Login!";
  32. }
  33. ?>

Creating our Login Success Page

Lastly, 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".

  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="index.php">Back</a>
  21. </body>
  22. </html>

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.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.