How to Create a PHP Login System for Your Website

Are you looking to create a login system on your website with PHP? Having a website login system allows access to important pages only to the registered users. The users must enter their credentials to access those important pages. For this, you need to create a login page for your website. This page will have a form where users can add their credentials and log in to the system. The logged-in user should also have the option to log out.

Basically, the login system needs to cover the below points.

  • Login form
  • Validate user’s credentials
  • For wrong credentials, display the error message.
  • If credentials are correct, redirect the user to the account page.
  • Log out the user

In this article, we will create a login system in PHP that will cover all the above steps. In order to handle all the mentioned points, we will use:

  • MySQL Database
  • PHP Sessions

The database contains the user’s information like email, password, full name, etc. We will check the user’s provided details against the records in the database. If a match is found, we will allow users to log into the system.

To keep users logged in to the application, we will set the user’s id into the PHP session. Using the value set in the Session, the system can recognize the user and keep them logged in.

Database Configuration

As I said, we require a MySQL database to store the user’s details. This tutorial mainly focuses on building a login system. So, I will create a database table and add a few dummy entries to it. I am not going to create a separate sign-up form and insertion code for it. For registration flow, the user can check out the article – PHP Registration System.

Run the below SQL which creates a users table in the MySQL database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `fullname` varchar(255) NOT NULL,
 `email` varchar(255) NOT NULL,
 `password` varchar(255) NOT NULL,
 `status` int(11) NOT NULL DEFAULT 1 COMMENT '1=Active|0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

If you notice, I have added 2 values for the status column.

  • 1 : It means, the user has activated their account.
  • 0 : This account is not activated yet.

We will allow only users with an active account to log into the system. The users with inactive accounts will see the error message on a login page.

Next, add the dummy rows to the users table by the below SQL.

INSERT INTO `users` (`fullname`, `email`, `password`, `status`) VALUES
('John Doe', 'john.doe@example.com', MD5('123456'), 1),
('Sam Doe', 'sam.doe@example.com', MD5('123456'), 0);

In SQL, I am using the MD5 hash version of a password. The password is kept as ‘123456’ for testing purposes. After creating a login form, you would try with the emails added above and this password.

Database Class (class-db.php)

To establish a database connection and check the user’s provided credentials against the database let’s create a class-db.php and add the following code to it.

<?php
class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
 
    public function __construct() {
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
 
    public function check_credentials($email = '', $password = '') {
        $sql = $this->db->query("SELECT id, fullname, status FROM users WHERE email = '$email' AND password = '". md5($password) ."'");

        if($sql->num_rows) {

            $result = $sql->fetch_assoc();

            if ('1' == $result['status']) {
                return array('status' => 'success', 'id' => $result['id'], 'fullname' => $result['fullname']);
            }

            return array('status' => 'error', 'message' => 'Your account is not activated yet.');
        }
        
        return array('status' => 'error', 'message' => 'Email or password is invalid.');
    }
}

Make sure to replace placeholders DB_HOST, DB_USERNAME, DB_PASSWORD, DB_PASSWORD, DB_NAME with their actual values. In the constructor, we wrote a code for database connection.

The method check_credentials() will accept parameters – email and password. It will check if credentials are correct or not and return the response accordingly.

Login Form (login.php)

The login form will have the inputs for email and password. The user has to fill in these details and hit a submit button. The server-side script will take these inputs, process them and handle the output.

<?php
session_start();

if (isset($_SESSION['user'])) {
    header('Location: myaccount.php');
}

require_once 'class-db.php';

$error_message = '';
if (isset($_POST['submit'])) {
    $db = new DB();
    $response = $db->check_credentials($_POST['email'], $_POST['password']);

    if ($response['status'] == 'success') {
        $_SESSION['user'] = array('id' => $response['id'], 'fullname' => $response['fullname']);
        header('Location: myaccount.php');
    }

    $error_message = ($response['status'] == 'error') ? $response['message'] : '';
}
?>

<?php if (!empty($error_message)) { ?>
    <div class="error">
        <strong><?php echo $error_message; ?></strong>
    </div>
<?php } ?>
<form method="post">
    <p>
        <label for="email">Email: </label>
        <input type="email" name="email" id="email" placeholder="Enter Email" required />
    </p>
    <p>
        <label for="password">Password: </label>
        <input type="password" name="password" id="password" placeholder="Enter Password" required />
    </p>
    <input type="submit" name="submit" value="Login" />
</form>

In the above code, on receiving a successful response I set the user id and fullname in the session variable ‘user’. PHP Sessions are available throughout the application. It helps us to recognize which user needs to keep logged in.

On successful login, the user will redirect to the myaccount.php. You can adjust this redirect page as per your flow.

The myaccount.php will simply have the welcome message and log-out link.

<?php
session_start();

if (!isset($_SESSION['user'])) {
    header('Location: login.php');
}
?>

<strong><?php echo 'Welcome, '. $_SESSION['user']['fullname']; ?></strong>
<p>
    <a href="logout.php">Log Out</a>
</p>

Logout User (logout.php)

The logout.php will remove the session variable ‘user’. As a result, this session variable will be empty and the application won’t keep the user logged in.

<?php
session_start();

if (isset($_SESSION['user'])) {
    unset($_SESSION['user']);
}

header('Location: login.php');

I hope you understand how to create a login system on your website with PHP. You can also extend this login functionality by integrating social login into your application. Have a look at the below articles which explain adding social login with PHP.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

8 thoughts on “How to Create a PHP Login System for Your Website

  1. Hello,
    Thank you so much for your useful videos and tutorials. However I have a question. How do I connect the three “.php” files into one HTML ? I am having trouble with this.
    Thank you very much for your help

  2. Really like and appreciate your work. I am trying to incorporate your code into a web site I’m creating, but having some problems. I keep throwing the “incorrect username or password” error message even if I use a valid username and password in my database. I’m almost an intermediate using mysql, php, html and css, but was wondering if you might be able to take a look at my code?

  3. Hello Sir,
    i know only html & css, but not idea about php. Can you help by mention where to put my site detail in your login system & how.

Leave a Reply

Your email address will not be published.