How to make a login php

Create a secure login page with PHP: learn how to make a simple login page with a username, password & example code.

Creating a Login Page using PHP

In this tutorial, we'll learn how to create a login page using PHP. We will be using a MySQL database to store our user information. Before we begin, let's take a look at the database structure we'll be using. We will have two tables:
  • Users - This table will contain user information such as username, password, email, etc.
  • Sessions - This table will store session information such as session ID, user ID, timestamp, etc.

Step 1: Connecting to the Database

The first step is to connect to the database. We'll do this by creating a new PHP file called db_connect.php. In this file, we'll add the following code:
<?php
  // Connect to MySQL
  $host = "localhost";
  $user = "username";
  $password = "password";
  $dbname = "database_name";

  $con = mysqli_connect($host, $user, $password, $dbname);

  // Check connection
  if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
In the code above, we are connecting to our database using the mysqli_connect() function. We are passing in four parameters: host, username, password, and database name. We are also checking to make sure that the connection was successful, and if not, we are displaying an error message.

Step 2: Creating the Login Form

Next, we'll create the login form. We'll create a new file called login.php. This file will contain a simple HTML form with two input fields: username and password. We'll also add a submit button. Here is the code:
<form action="login.php" method="post">
  <input type="text" name="username" placeholder="Username">
  <input type="password" name="password" placeholder="Password">
  <input type="submit" name="submit" value="Login">
</form>

Step 3: Validating the User

Now we'll add some PHP code to validate the user. We'll add the following code to the login.php file:
<?php
  // Include database connection file
  include_once 'db_connect.php';

  // Check if the form is submitted
  if (isset($_POST['submit'])) {
    // Get the username and password from the form
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Validate the user
    $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
    $result = mysqli_query($con, $sql);

    // Check if the user exists
    if (mysqli_num_rows($result) > 0) {
      // User exists, log them in
      // Redirect to protected page
    } else {
      // User does not exist
      // Display error message
    }
  }
?>
In the code above, we are checking to see if the form has been submitted. If it has, we are getting the username and password from the form. We are then running a SQL query to see if the user exists in the database. If the user does exist, we will log them in and redirect them to a protected page. If the user does not exist, we will display an error message.

Step 4: Logging the User In

Now that we have validated the user, we can log them in. To do this, we'll create a session for the user and store the session information in our sessions table. We'll also set a cookie on the user's browser to keep them logged in. Here is the code:
<?php
  // Get the user ID
  $user_id = mysqli_fetch_assoc($result)['id'];

  // Generate a random session ID
  $session_id = md5(uniqid(rand(), true));

  // Store the session in the database
  $sql = "INSERT INTO sessions (user_id, session_id, timestamp) VALUES ('$user_id', '$session_id', NOW())";
  mysqli_query($con, $sql);

  // Set the session cookie
  setcookie("session_id", $session_id, time() + (86400 * 30), "/");
?>
In the code above, we are getting the user's ID from the query result. We are then generating a random session ID and storing it in the database. Finally, we are setting a cookie on the user's browser with the session ID. This will keep them logged in for 30 days.

Step 5: Redirecting the User

Finally, we'll redirect the user to the protected page. To do this, we'll use the header() function. Here is the code:
<?php
  // Redirect the user to the protected page
  header("Location: protected.php");
  exit;
?>
In the code above, we are redirecting the user to the protected page using the header() function. And that's it! We have now created a login page using PHP. We have connected to the database, created a login form, validated the user, logged the user in, and redirected the user to a protected page.

Answers (0)