User Login, Registration and Logout System using PHP for Beginners

User Login, Registration and Logout System using PHP for Beginners

In this article, you will learn how to make a Login and Registration system using PHP. If you are a beginner then you are the right place.

Disclaimer: This lesson does not contain Validation and Sanitization because this is a beginner’s tutorial and its only focus is to teach how we make the Login and Registration system using PHP.
Validation and Sanitization will be covered in this tutorial’s second part, which will have some advance methods and security.

Requirements

  • Some Basic Knowledge of
    • HTML
    • MySQL
    • PHP
  • A simple IDE or Text Editor (Like Sublime Text, Notepad++, Notepad, etc.)
  • that’s it

Pages we are going to make

  • index.php (Home Page with Login and Registration Forms)
  • register.php (Registration Page)
  • login.php (Login Page)
  • logout.php (Logout Page)

To start making a Login and Registration system using PHP, your computer should have PHP, Apache Server and MySQL installed in it.

If your computer does not have PHP, Apache Server and MySQL installed in it, then simply see my article on How to install PHP, Apache Server and MySQL in Windows.

Let’s start!

  • Start your Apache Server and MySQL Server in your PC.
  • Open your Text Editor, I will be using Sublime Text.
  • Create as an Index page or you can say a Home page with HTML Form and save it as a PHP file in your Server Directory. See the code below for index.php.

If you want to download Sublime Text editor, you can download it from here. Download Sublime Text Editor

<!-- Home Page "index.php" -->

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1>Home Page</h1>
        <hr>
        <h4>Register</h4>
        <form action="register.php" method="POST">
            <label>Name:
                <input type="text" name="user_name">
            </label>
            <label>Email:
                <input type="email" name="user_email">
            </label>
            <label>Password:
                <input type="password" name="user_password">
            </label>
            <input type="submit" value="Register">
        </form>
    </body>
</html>

If you didn’t understand what this following does? don’t worry, I will explain it to you.

Hope you have a basic knowledge of HTML to understand the basic HTML tags.

Let’s start from the Form Element.

We have created a form which will send its data to the page given to its action attribute.

Also, the method attribute shows that the data will be sent as a POST request to register.php page.

Which means the user will not be able to see how the details got transferred to register.php page because we have used POST in method attribute.

The most important part is to specify unique names to each input field of the form, as we have done here.

We have set name attribute to all our input field tags, such as,
for the “Name” of the user we used name="user_name",
for the “Email” of the user we used name="user_email" and
for the “Password” of the user’s account we used name="user_password".

But why giving names to these input fields are necessary?

giving a unique name to each input field is necessary because these names will be used to fetch data on register.php page so that we can store those details entered by the user.

Then, we have added a button to let the user submit the details by the following code.

Now, Let’s make a database demo to store the details entered by the users.

Hope you have a basic knowledge of MySQL.

I have already created a MySQL database named demo and inside it, we have to create a table with the following details.

# Table users

create table users(
'id' INT(10) PRIMARY KEY AUTO_INCREMENT,
'name' VARCHAR(255),
'email' VARCHAR(255) UNIQUE,
'password' VARCHAR(255)
);

To save time and energy, you can do it with PhpMyAdmin which is an inbuilt application comes with XAMPP, WAMP and EasyPHP software.

Okay, now we have our database ready to store our user’s details.

Here we have completed part 1 of the tutorial Login and Registration system using PHP.

Part 2 of the tutorial “Login and Registration System using PHP”.

Now let’s create a register.php page with PHP to store data into our database.

In your text editor, create a new file and save it as register.php in the same folder where we have saved our Home Page index.php as shown in the image below.

Now, enter the following code in register.php page to start receiving data from index.php page entered by the user in the registration form.

Let’s test if it is working or not, and see how we will get the data from index.php page.

Enter the following code in the register.php page.

<!--Register Page "register.php"-->

<?php
    print_r($_POST);
?>

Now, enter some random details on index.php page and try submitting the details.
If you can see the same text you entered in the form here, then you are doing it right, if not? then you have made a mistake somewhere.

If it didn’t work try to match the codes,
see that both the pages are in the same folder,
and see that you are accessing the pages through your localhost server.

If it still didn’t work, explain the issue you are getting in the comments section below with your email id so that I can send you the solution. I will reply to as fast as I can.

If it’s working, let’s proceed further with the user’s registration system.
With print_r($_POST); function, we can see that the data is coming in an Array format and we can fetch the single record by modifying the codes as shown below.

Replace print_r($_POST); with the lines shown below.

<!-- Registration page "register.php" -->
<?php
    // Fetch data from $_POST array
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $password = $_POST['user_password'];

    // Print data on page
    echo "<p>".$name."</p>";
    echo "<p>".$email."</p>";
    echo "<p>".$password."</p>";
?>

Now, you can fetch the particular field’s data from the $_POST array.

I hope now you know how to tackle with $_POST array and fetch the data sent via POST requests.

To save this data in our Database first we have to link our register.php with our database and execute the insert queries to insert new records in the users table.

But how do we link a PHP file with a database?

Let’s see…

Actually, there are two PHP Classes of MySQL are already installed with PHP, which comes with all the possible functions/methods required to execute any type of MySQL query into the database.

  1. MySqli (it is replaced by old “MySQL” class, the “i” stands for “improved”)
  2. PDO

We are going to use the mysqli class for this beginner’s lesson.

You should also know that you can use the mysqli class in two types

  1. Procedural method
  2. Object-Oriented method

We will use the Object-Oriented method because of it easy to learn and simple.

So, first we will make an instance or you can say we will make a copy of that class and store it into a variable, and we will use that copy everywhere to perform our Database queries.

Since we are a making copy of that MySQL Class, it is going to include all its functions/methods also with it.

Okay, Let’s start now,

Add the following lines to your register.php page.

<!--Register Page "register.php"-->
<?php

    // Fetch data from $_POST array
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $password = $_POST['user_password'];

    // $sql = new mysqli("your_server_name", "username_of_your_MySQL_database", "password_of_the_MySQL_database", "database_name");
    $sql = new mysqli("localhost", "root", "123","demo");

?>

Here we have made a copy of the mysqli class.

But how do we check if it actually established a connection? and if not then how do we check if connection id failed.

Also, remember that we have to close the Database connection after doing our all database work by using the close() method of the mysqli class.

There are some methods in the mysqli class to check database connection, shown below.

<!--Register Page "register.php"-->
<?php

    // Fetch data from $_POST array
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $password = $_POST['user_password'];

    // $sql = new mysqli("server_name", "username_of_MySQL_database", "password_of_MySQL_database", "database_name");
    $sql = new mysqli("localhost", "root", "123","demo");

    // Checks MySQL Databse connection
    if ($sql->connect_error) {
        // If connection failed, stop the execution of whole page
        die("Database connection failed: " . $sql->connect_error);
    }

    $sql->close();
?>

Here in if statement we have passed $sql->connection_error which will return the error occurred. If the error method has something, the if statement gets True and executes the die() function in it.

This die() function will output the data passed in its parentheses () and stop the execution of the page.

Now, we have made a connection to the database and checked the connection for errors.

Now let’s insert new records in the users table.

The following codes will insert the new record in the users table.

<!--Register Page "register.php"-->
<?php

    $query = "INSERT INTO users(name, email, password) VALUES('{$name}', '{$email}', '{$password}')";
    $sql->query($query);

?>

But what we have done here?

We created a query string and stored it into the $query variable. In this string we have passed $name, $email and $password variables in which we have stored the data we got from our $_POST request variable.

After that we will execute the query using query() method of the mysqli class and passing the Query string we made into its parentheses () as shown in the line $sql->query($query);

But wait,

How we will check if the data is stored in the database, and if not, then we have to tell the users that their registration has failed so that they can try again.

There is how we do it.

The query() method of mysqli class returns a Boolean value in True or False whenever a query is executed. If the query is successful it returns True otherwise, it returns False. So, we can make use of that, by surrounding it with if-else statements.

Let’s see how…

<!--Register Page "register.php"-->
<?php

    $query = "INSERT INTO users(name, email, password) VALUES('{$name}', '{$email}', '{$password}')";

    if($sql->query($query)){
        echo "Regsitered successfully.";
    }
    else{
        echo "Something went wrong! Please try again";
    }

?>

Now we can track our record.

Till now, your “register.php” should look like this.

<!--Register Page "register.php"-->
<?php
    // Fetch data from $_POST array
    $name = $_POST['user_name'];
    $email = $_POST['user_email'];
    $password = $_POST['user_password'];

    // $sql = new mysqli("your_server_name", "username_of_your_MySQL_database", "password_of_the_MySQL_database", "database_name");
    $sql = new mysqli("localhost", "root", "123","demo");

    // Checks MySQL Databse connection
    if ($sql->connect_error) {
        // If connection failed, stop the execution of whole page
        die("Database connection failed: " . $sql->connect_error);
    }

    $query = "INSERT INTO users(name, email, password) VALUES('{$name}', '{$email}', '{$password}')";
    
    if($sql->query($query)){
        echo "Regsitered successfully.";
    }
    else{
        echo "Something went wrong! Please try again";
    }

    $sql->close();
?>

Now you can test it in the browser.

Here we have completed part 2 of the tutorial Login and Registration system using PHP.

Part 3 of the tutorial “Login and Registration System using PHP”.

Now let’s add login form in Home Page which we have saved as index.php

<!-- Home Page "index.php" -->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Home</title>
    </head>
    <body>
        <h1>Home Page</h1>
        <hr>

        <h4>Login</h4>
        <form action="login.php" method="POST">
            <label>Email:
                <input type="email" name="login_email">
            </label>
            <label>Password:
                <input type="password" name="login_password">
            </label>
            <input type="submit" value="Login">
        </form>
        <hr>

        <h4>Register</h4>
        <form action="register.php" method="POST">
            <label>Name:
                <input type="text" name="user_name">
            </label>
            <label>Email:
                <input type="email" name="user_email">
            </label>
            <label>Password:
                <input type="password" name="user_password">
            </label>
            <input type="submit" value="Register">
        </form>
    </body>
</html>

Here we added the Login form and passed a new page login.php into its action attribute and method is the same POST. Since we don’t want the password of the user to be shown to nearby people and it is very important.

In the input fields, we have an Email field with the name login_email and a Password field with the name login_password set in their name attributes.

And of course, a submit button with the value Login.

Now let’s make a new file in our text editor and save it with the name login.php.

Now in our login.php page, we are going to do some of the same jobs as done in register.php page.

Why? it is because then we are going to receive Email and Password from the user again, but this time for the Login purpose and we will have to see in the database if the user has entered the correct Email and Password.

If the details are correct then we will make them log in.

But this time, we don’t have to insert any record in the database, we just have to fetch the data of the user from the database.

Okay, let’s start now.

<!--Login Page "login.php"-->
<?php
    
    // fetching user data from the $_POST request variable
    $email = $_POST['login_email'];
    $password = $_POST['login_password'];

    // creating a mysqli class copy
    // $sql = new mysqli("server_name","username_of_MySQL_database","password_of_MySQL_database","database_name");
    $sql = new mysqli("localhost","root","123","demo");

    // Checks MySQL Databse connection
    if ($sql->connect_error) {
        // If connection failed, stop the execution of whole page
        die("Database connection failed: " . $sql->connect_error);
    }

    $sql->close();
?>

Most of the codes are same as in register.php page, you can copy and paste them.

But keep in mind that the login details we are receiving here are coming with the different names this time because we have set the name attributes of the input fields as login_email and login_password.

Now we will use the SELECT statement of MySQL to search the user’s account in our database with his/her email and password, if the record founds, we will them logged in.

Let’s see how…

<!--Login Page "login.php"-->
<?php
    
    $query = "SELECT id,name,email FROM users WHERE email={$email} AND password={$password}";
    $records = $sql->query($query);

?>

Here instead of using if-else for the query() method, we are storing its result in a variable $records. It is because here we have used the SELECT statement which provides a MySQL object containing the query results, so we have to store that result object in a variable.

After this, we will check if the record is found with those user’s credentials by using num_rows method on the object we have stored in the $records variable.

<!--Login Page "login.php"-->
<?php
    
    $query = "SELECT id,name,email FROM users WHERE email={$email} AND password={$password}";
    $records = $sql->query($query);

    if ($records->num_rows > 0) {
        echo "Correct Email and Password";
    }else{
        echo "Incorrect Email and Password";
    }

?>

But wait,
Instead of showing users that they have entered correct details, we have to show their name and email on the page to let them know into which account the user has logged in.

But how do we get the user’s name?
Simple…
From our database.

As we have fetched the results using the SELECT query, the details of the user are already there.

To fetch the details for the user from the results object which we have saved in the $records variable, we will have to use the fetch_assoc() method on the object and this will return an array containing the details of the user.

But you have to keep in mind that, then this will be an associative array which looks like this.

<?php
    $array = [
        "id"=>"5"
        "name"=>"DesignoFox",
        "email"=>"hello@example.com",
    ];
?>

If the SELECT query returns 1 row or record the fetch_assoc() method will also return 1 array, but it SELECT query returns many rows or records then the fetch_assoc() method will also return the same amount of associative arrays.

But in our case, we will not have so many accounts with the same email, if you know why? lets others also in the comments below.

Okay, let’s see how to fetch data using fetch_assoc() method.

<?php
    // Query string    
    $query = "SELECT id,name,email FROM users WHERE email={$email} AND password={$password}";
    // execute the query and store results in a variable
    $records = $sql->query($query);

    $user_record = $records->fetch_assoc();
    $loggedin_user_id = $user_record['id'];
    $loggedin_user_name = $user_record['name'];
    $loggedin_user_email = $user_record['email'];

?>

This was simple, hope you figured it out how it worked.

After this we have to create a session for the User till they are logged in, so that the website could determine whether the user has already logged in or not, for that we will use the $_SESSION[] variable which is a Global PHP variable and can be accessed on all the PHP pages within the same server name like example.com (in our case it is localhost).

This is simple, we just have to store the user details of currently logged in user in the form of an array.

But first we have start the PHP Session system by unsing a simple function session_start() before using $_SESSION[] variable.

Like this

<?php

    // start the PHP Session system
    session_start();

    // store the array in $_SESSION[] variable
    $_SESSION['loggedin'] = [
        "id"=>$loggedin_user_id,
        "name"=>$loggedin_user_name,
        "email"=>$loggedin_user_email
    ];

?>

thats it!

Let’s combine all those codes and make the user really log in.

<!--Login Page "login.php" complete code-->
<?php
    
    // fetching user data from the $_POST request variable
    $email = $_POST['login_email'];
    $password = $_POST['login_password'];

    // creating a mysqli class copy
    // $sql = new mysqli("server_name","username_of_MySQL_database","password_of_MySQL_database","database_name");
    $sql = new mysqli("localhost","root","123","demo");

    // Checks MySQL Databse connection
    if ($sql->connect_error) {
        // If connection failed, stop the execution of whole page
        die("Database connection failed: " . $sql->connect_error);
    }

    // Query string    
    $query = "SELECT id,name,email FROM users WHERE email={$email} AND password={$password}";

    // execute the query and store results in a variable
    $records = $sql->query($query);

    // check any record exists with those email and password
    if ($records->num_rows > 0) {

        // user logged in here
        $user_record = $records->fetch_assoc();
        $loggedin_user_name = $user_record['name'];
        $loggedin_user_email = $user_record['email'];        

        // start the PHP Session system
        session_start();

        // store the users data in $_SESSION[]
        $_SESSION['loggedin'] = [
            "id"=>$loggedin_user_id,
            "name"=>$loggedin_user_name,
            "email"=>$loggedin_user_email
        ];

        echo "<div>You are logged in " . $_SESSION['loggedin']['name'] . "</div>";
        echo "<div>Your email is " . $_SESSION['loggedin']['email'] . "</div>";
        echo "<div><a href='logout.php'>Logout</a></div>";
    }
    else{
        // email or password is wrong
        echo "Incorrect Email and Password";
    }

    // close the database connection
    $sql->close();
?>

Here we finished Part 3, of the tutorial Login and Registration system using PHP.

Here comes part 4 the tutorial “Login and Registration System using PHP”, which is the last/
It will be the shortest one.

Make a new file in your text editor and save it as logout.php in the same folder.

In the logout system, we will simply delete the Session we store in $_SESSION[] variable.

But before using $_SESSION[] variable we have to start the PHP Session system for this page by using session_start() function.

Here is how the logout.php will be created.

<!--logout.php-->
<?php 

    // starts PHP session system
    session_start();

    // unset or remove the loggedin array from Session variable
    unset($_SESSION['loggedin']);

    // redirect the user to index.php page which is our home page
    header("location:index.php");

?>

Just add a little piece of code on the top of the “index.php” page to redirect if already logged in.

<!--"index.php"-->
<?php

    if ($_SESSION['loggedin']['name'] != "") {
        header("location:login.php")
    }

?>

and modify login.php as shown below.

<!-- Modified login.php -->
<?php
    
    // fetching user data from the $_POST request variable
    $email = $_POST['login_email'];
    $password = $_POST['login_password'];

    // creating a mysqli class copy
    // $sql = new mysqli("server_name","username_of_MySQL_database","password_of_MySQL_database","database_name");
    $sql = new mysqli("localhost","root","123","demo");

    // Checks MySQL Databse connection
    if ($sql->connect_error) {
        // If connection failed, stop the execution of whole page
        die("Database connection failed: " . $sql->connect_error);
    }

    // Query string    
    $query = "SELECT id,name,email FROM users WHERE email={$email} AND password={$password}";

    // execute the query and store results in a variable
    $records = $sql->query($query);

    // check any record exists with those email and password
    if ($records->num_rows > 0) {

        // user logged in here
        $user_record = $records->fetch_assoc();
        $loggedin_user_name = $user_record['name'];
        $loggedin_user_email = $user_record['email'];        

        // start the PHP Session system
        start_session();

        // store the users data in $_SESSION[]
        $_SESSION['loggedin'] = [
            "id"=>$loggedin_user_id,
            "name"=>$loggedin_user_name,
            "email"=>$loggedin_user_email
        ];

    }
    else{
        // email or password is wrong
        echo "Incorrect Email and Password";
    }

    // Account info
    // if the user is already loggedin
    if ($_SESSION['loggedin']['name'] != "") {
        echo "<div>You are logged in " . $_SESSION['loggedin']['name'] . "</div>";
        echo "<div>Your email is " . $_SESSION['loggedin']['email'] . "</div>";
        echo "<div><a href='logout.php'>Logout</a></div>";
    }

    // if the user is not loggedin
    else{
        echo "<div>Please login first!</div>";
        echo "<div><a href='index.php'>Click Here to Login</a></div>";
    }


    // close the database connection
    $sql->close();
?>
Thank You! Please give your feedback below in the comments.
So that we can improve our tutorials for you to understand better.

 

Summary
Login, Registration and Logout System using PHP for Beginners
Article Name
Login, Registration and Logout System using PHP for Beginners
Description
Login, Registration and Logout System using PHP for Beginners
Author
Publisher Name
DesignoFox
Publisher Logo

Vikas Vimal

Web Designer and Developer from India. Music and Food Lover.

This Post Has 2 Comments

  1. Yash Sharma

    This is the best PHP tutorial on login and registration system. I’ve read many tutorials online but this is one of the best tutorial on PHP login and registration system.

  2. Vikki

    Very good tutorial, must read for beginners in PHP…

Want to say something? Tell us in the comments section below.