How to create a user login system with HTML, PHP, & MySQL

 

 

Hello there and welcome to Code Bulletin!

 

Today we're going to build an awesome, fully-functional user login system using three amazing web technologies: HTML, PHP, and MySQLi. We will use HTML to design the login form and user profile. We will use a MySQLi database to store the user account information and we'll use PHP to communicate with that database and power the backend.

 

This tutorial will consist of the following six stages...

1.   Creating the registration, login, and profile pages with HTML and CSS.

2.   Constructing the MySQLi database with a simple PHP script.

3.   Powering the registration page with PHP and MySQL.

4.   Powering up the login page.

5.   Making the profile page dynamic.

6.   Developing the "Log Out" script.

So enough of the boring stuff. Let's write some code!

 

 

 

 

Creating the Registration Page

 

To begin, create a new file and name it "register.php".

 

The first thing we need to do is create the barebones structure of the document.

 

 

<!DOCTYPE html>

 

<html>

<head>

 

</head>

<body>

 

</body>

</html>

 

 

The <head> will contain "behind the scenes" attributes, resources, and information about the document, while the <body> will hold the actual visible webpage itself.

 

The next thing we do is add a page title and link to our style sheet (this will be created later).

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>Register</title>  <!-- The page title displayed in the browser tab -->

</head>

<body>

 

</body>

</html>

 

 

Finally, we’ll add the registration form itself.

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>Register</title>  <!-- The page title displayed in the browser tab -->

</head>

<body>

<form action=”submit_registration.php” method=”POST”>  <!-- This <form> element contains the text boxes and submit button. When the submit button is pressed, its job is to send the information to the specified script. -->

Username: <input type=”text” name=”username”>  <!-- Input text box for the username -->

<br><br>  <!—Adding two line breaks -->

Email: <input type=”text” name=”email”>  <!-- Text box for the user’s email address -->

<br><br>

Password: <input type=”password” name=”password”>  <!-- This input box is of the type “password” which means that the characters will be censored -->

<br><br>

<input type=”submit” name=”submit”>  <!-- The type here is “submit” which means that the <form> will be processed as soon as the button is pressed -->

</form>  <!-- Closing the <form> -->

</body>

</html>

 

 

That’s it. Here is the finalized version without comments…

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>Register</title>  <!-- The page title displayed in the browser tab -->

</head>

<body>

<form action=”submit_registration.php” method=”POST”>

Username: <input type=”text” name=”username”>

<br><br>

Email: <input type=”text” name=”email”>

<br><br>

Password: <input type=”password” name=”password”>

<br><br>

<input type=”submit” name=”submit”>

</form>

</body>

</html>

 

The next step is to code the “login.php” page…

 

 

 

 

Creating the Login Page

 

Start by creating a new filed titled "login.php".

 

Once again, we will start with a barebones structure.

 

 

<!DOCTYPE html>

 

<html>

<head>

 

</head>

<body>

 

</body>

</html>

 

 

We then add our page title and link to the stylesheet that will be created later.

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>Register</title>  <!-- The page title -->

</head>

<body>

 

</body>

</html>

 

 

We then create the login form which is very similar to the registration form we created earlier.

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>Login</title>  <!-- The page title displayed in the browser tab -->

</head>

<body>

<form action=”submit_login.php” method=”POST”>  <!-- Our <form> element sends submitted data to “submit_login.php” which we will create later -->

Username or Email: <input type=”text” name=”usernameoremail”>  <!-- Input text box for the member’s username or email address -->

<br><br>  <!—Adding two line breaks -->

Password: <input type=”password” name=”password”>  <!-- This is where the user types his or her password -->

<br><br>

<input type=”submit” name=”submit”>  <-- This is our “submit” button -->

</form>

</body>

</html>

 

 

That’s it. Here is the finalized version without comments…

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>Login</title>  <!-- The page title displayed in the browser tab -->

</head>

<body>

<form action=”submit_login.php” method=”POST”>

Username or Email: <input type=”text” name=”usernameoremail”>

<br><br>  <!—Adding two line breaks -->

Password: <input type=”password” name=”password”>

<input type=”submit” name=”submit”>

</form>

</body>

</html>

 

 

Now that we’ve finished the login page, it’s time to create the user profile page.

 

 

 

 

Creating the User Profile Page

 

The profile page will be very simple and will display the member’s username and email address. The primary purpose of this is to show you how to extract data from a MySQL/MySQLi database and use it on an HTML document.

 

Begin by creating a file named “profile.php”.

 

As always, we start with the basic HTML document structure.

 

 

<!DOCTYPE html>

 

<html>

<head>

 

</head>

<body>

 

</body>

</html>

 

 

We add the title and style sheet reference to the <head>.

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>(username) | Profile</title>  <!—Later on we will add a dynamic variable to display the member’s username in the page title -->

</head>

<body>

 

</body>

</html>

 

 

Now here’s where we dig into something new. We don’t need any <form> elements since the user is not inputting information. Instead, we need to display the information that the user provided earlier. We will not actually add the dynamic PHP code just yet. Instead we’ll simply prepare the HTML and have the profile page ready to roll as soon as it’s time for the PHP.

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>(username) | Profile</title>  <!—Later on we will add a dynamic variable to display the member’s username in the page title -->

</head>

<body>

    <h1>Your Profile</h1>  <!-- Add the page heading -->

    <br>  <!-- Create a page break -->

    <div>Hello there <b>(username here)</b>, welcome to your profile page!</div>  <!-- Later on we will replace (username here) with a dynamic PHP variable -->

    <br><br>  <!-- Add two more page breaks -->

    <div>Your email address is <b>(email here)</b>.</div>  <!-- The same thing here. A dynamic variable will be used. -->

    <br><br>  <!-- Add two more page breaks -->

    <div><a href=”logout.php”>Logout</a></div> <!-- Create a link to the logout script which we will create later. -->

</body>

</html>

 

 

Here is a clean version without comments or highlighting…

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>(username) | Profile</title>

</head>

<body>

    <h1>Your Profile</h1>

    <br>

    <div>Hello there <b>(username here)</b>, welcome to your profile page!</div>

    <br><br>

    <div>Your email address is <b>(email here)</b>.</div>

    <br><br>

    <div><a href=”logout.php”>Logout</a></div>

</body>

</html>

 

 

We’re now finished with the front end work. It’s time to create our database…

 

 

 

 

Creating the MySQL Database

 

It’s now time to design and create the database that will power our site.

 

Start by entering your server control panel (typically cPanel) and find “MySQL Database”. Enter the application and create a new database. You can name your database whatever you like. For this tutorial I’ll name mine “ex_database”.

 

The step is to create a MySQL user and attach it to the database. Give this user all privileges. For this tutorial I created a user with the username “ex_admin” and the password “ex_password”.

 

Now that this is complete we need to populate our database with the necessary tables. You can complete this exact process directly via phpMyAdmin, but we’ll be taking a different route. We’ll be creating the database via a PHP script. While creating a database via phpMyAdmin might seem easier and simpler at first, it’s not an easily repeatable process. You can create a database on a specific server, but if your script is used on a separate server then you’ve got to repeat the process and recreate all of those tables. With a script, we can simply run that script on any server, and it will automatically structure our database in only a few seconds.

 

Now, before we can start interacting with the database via PHP, we need to create a connection script. Any time we need to interact with the database, we will reference this script to establish the necessary connection.

 

Go to the root directory of your site (usually the “public_html” folder) and create a new file named “conn.php”.

 

Open the file and fill it with the following code…

 

 

<?php

 

//Each of the following variables will hold the necessary information for successful database connection.

$db_host = “your database host (almost always ‘localhost’)”;

$db_user = “the username of the MySQL user connected to the database”;

$db_pass = “the password of the MySQL user”;

$db_name = “the name of your database”;

 

//Initiate the MySQLi connection by providing the host, user, user password, and database name.

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

 

//This piece of code will check for any problems connecting to the database. If any issues are encountered then this code will display an error message and exit the script.

if(!$conn){

    echo “Sorry, we encountered an issue connecting to the database!”;

    exit();

}

 

?>

 

 

Here is a clean version of the script with the database information that I used. You will need to modify it if any of those values differ from the ones I used.

 

 

<?php

 

$db_host = “localhost”;

$db_user = “ex_admin”;

$db_pass = “ex_password”;

$db_name = “ex_database”;

 

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

if(!$conn){

    echo “Sorry, we encountered an issue connecting to the database!”;

    exit();

}

 

?>

 

 

Now that the connection file is all ready to go, we can code our database structuring script.

 

Begin by creating a new file and naming it “sql.php”.

 

Open the empty file.

 

Here is the first piece of code we will add…

 

<?php

 

//Include our connection script which will initiate a database connection automatically.

include_once(conn.php”);

 

//The following code is essentially a query against the database that will create a table named ‘users’ that has six fields. The “id” field is an automatically incrementing field that provides each row with a unique identification number (hence type “INT”). The “username” field is of the data type “VARCHAR” which is used to store relatively short bits of text. Long blocks of text that are over 500 words should be store via TEXT. Usernames are usually a lot shorter than that which is why we’re using the VARCHAR data type. We’ve also assigned it a maximum character length of 255. We did the exact same thing with the “email” and “password” fields since they are very similar. We then have the last field which is “registration_date”. This is of the data type “DATETIME” which is used to store a date and/or time in the DATETIME format. You should also notice that all of these fields are “NOT NULL”. This simply means that they are supposed to always contain information. They are designed to never be “null”. Hence “not null”. Finally, we define the primary key. Since an “id” number is always unique, we will use it as the primary key for our table.

$table_users = mysqli_query(“CREATE TABLE IF NOT EXISTS ‘users’

    id INT(11) NOT NULL AUTO_INCREMENT,

    username VARCHAR(255) NOT NULL,

    email VARCHAR(255) NOT NULL,

    password VARCHAR(255) NOT NULL,

    registration_date DATETIME NOT NULL,

    PRIMARY_KEY(id)

“);

 

//Here, we check for any errors during the table creation process. If any are encountered then we display an error message. If everything runs smoothly then we display a success message.

if(!$table_users){

echo “Sorry, we encountered an error creating the table ‘users’.”;
} else {

echo “The table ‘users’ was created successfully.”;
}

 

//Close the database connection so we don’t eat up server resources.

mysqli_close($conn);

 

?>

 

 

Here is a clean version of the code…

 

 

<?php

 

include_once(conn.php”);

 

$table_users = mysqli_query(“CREATE TABLE IF NOT EXISTS ‘users’

    id INT(11) NOT NULL AUTO_INCREMENT,

    username VARCHAR(255) NOT NULL,

    email VARCHAR(255) NOT NULL,

    password VARCHAR(255) NOT NULL,

    registration_date DATETIME NOT NULL,

    PRIMARY_KEY(id)

“);

if(!$table_users){

echo “Sorry, we encountered an error creating the table ‘users’.”;
} else {

echo “The table ‘users’ was created successfully.”;
}

 

mysqli_close($conn);

 

?>

 

 

Save the file and then navigate to “yoursite.com/sql.php”. Once the file finishes running and the success message has been displayed, your database should be ready to start storing user accounts. If you encountered any errors then please visit the debugging guide for this tutorial here. Otherwise, hop over to phpMyAdmin on your server and enter the database you created earlier. You should see this…

 

Enter the table itself and you should see this…

 

If everything is all there, then we are ready to move on to the next phase…

 

 

 

 

Powering the Registration Page

 

This section is where we power up “register.php” and make it actually work. After we’re finished your registration form will be able to actively store user accounts in the database.

 

To begin, create a file and give it the luscious name “submit_registration.php”.

 

Enter the file and write the following code…

 

 

<?php

   

    //Open the connection.

include_once(conn.php”);

 

//We first check whether or not the form has been submitted by asking if the $_POST data is available. If that is indeed the case, then we execute necessary code.

if(isset($_POST[‘submit’])){

 

//Here we store the POST data sent from the form into relevant variables. You may also notice that crazy long function “mysqli_real_escape_string()”. This function protects your site from a type of hack known as “MySQL Injection”. This is a very dangerous hack and leaving your site vulnerable could spill disaster. Whenever you insert data into a database that was received from the user, you should ALWAYS run it through this function first. For more information on MySQL injections please visit this <a>link</a>.

$username = mysqli_real_escape_string($conn, $_POST[‘username’]);

$email = mysqli_real_escape_string($conn, $_POST[‘email’]);

$password = mysqli_real_escape_string($conn, $_POST[‘password’]);

        

//In the following block of code we check for 3 conditions. First we “ask” if the username entered is less than 1 character in length. We use the “strlen()” function to do this. If the length is less than 1 character long, then we know that the user failed to fill out the form. In that case we exit the script and send back the error message “Please enter a valid username.” In the second condition we ask if the username is less than 3 characters long. If that’s the case, then we know that the user entered a username but failed to attain the minimum username length which is 3. In that scenario, we issue back an error message saying as much and “exit()” so that no further action is taken. Finally, we check whether or not the username is longer than 25 characters. If so, we exit the script and send the relevant error message.

if(strlen($username) < 1){

echo “Please enter a valid username.”;

exit();
} else if(strlen($username) < 3 {

echo “Your username must be at least 3 characters in length.”;

exit();
} else if(strlen($username) > 25) {

echo “Your username cannot be more than 25 characters in length.”;

exit();
}

        

//Here we do the same sort of checks with the email as we did with the username. Just checking minimum and maximum character lengths.

if(strlen($email) < 6){

echo “Please enter a valid email address.”;
} else if(strlen($email) > 50) {

echo “Your email address cannot be more than 50 characters in length.”;
}

        

         //Once again, just checking valid input.

if(strlen($password) < 1){

echo “Please enter a password.”;
} else if(strlen($password) < 6) {

echo “Your password must be at least 6 characters in length.”;
} else if(strlen($password) > 25) {

echo “Your password cannot be more than 25 characters in length.”;
}

        

//This variable holds the MySQl command that we will execute next.

$sql = “INSERT INTO users (username, email, password, registration_date) VALUES (‘$username’, ‘$email’, ‘$password’, ‘$time’)”;

 

//Here we execute the MySQL query using our database connection variable and MySQL command variable.

         $query = mysqli_query($conn, $sql);

 

//If the query is unable to complete successfully then we print a relevant error message onto the screen. “Else” if it DID complete successfully, then we let the user know that their account was created successfully. We also use the dynamic “$username” variable in the text so that the user’s screen name is included in the message.

    if(!$query){

echo “Sorry, we were unable to complete your registration do to a database error.”;

} else {

echo “<b>$username</b>, your account was created successfully!”;

}


}

 

//Close the connection.

mysqli_close($conn);

 

?>

 

 

Below is the clean code…

 

 

<?php

   

include_once(conn.php”);

 

if(isset($_POST[‘submit’])){

 

$username = mysqli_real_escape_string($conn, $_POST[‘username’]);

$email = mysqli_real_escape_string($conn, $_POST[‘email’]);

$password = mysqli_real_escape_string($conn, $_POST[‘password’]);

          

if(strlen($username) < 1){

echo “Please enter a valid username.”;

exit();
} else if(strlen($username) < 3 {

echo “Your username must be at least 3 characters in length.”;

exit();
} else if(strlen($username) > 25) {

echo “Your username cannot be more than 25 characters in length.”;

exit();
}

 

if(strlen($email) < 6){

echo “Please enter a valid email address.”;
} else if(strlen($email) > 50) {

echo “Your email address cannot be more than 50 characters in length.”;
}

        

if(strlen($password) < 1){

echo “Please enter a password.”;
} else if(strlen($password) < 6) {

echo “Your password must be at least 6 characters in length.”;
} else if(strlen($password) > 25) {

echo “Your password cannot be more than 25 characters in length.”;
}

          

$sql = “INSERT INTO users (username, email, password, registration_date) VALUES (‘$username’, ‘$email’, ‘$password’, ‘$time’)”;

         $query = mysqli_query($conn, $sql);

    if(!$query){

echo “Sorry, we were unable to complete your registration do to a database error.”;

} else {

echo “<b>$username</b>, your account was created successfully!”;

}


}

 

mysqli_close($conn);

 

?>

 

 

In the next step we’ll create a PHP script to power up the login page just like we did above.

 

 

 

 

Powering Up the Login Page

 

We will now create a PHP script to process the information provided by the user when they login. This information is sent via the <form> element in “login.php”.

 

Create a new file and name it “submit_login.php”.

 

Open the file and write the following code…

 

 

<?php

   

    //Initiate the database connection.

include_once(conn.php”);

 

//Check for user input from our form. If no input has been received then there’s no reason to run the code.

if(isset($_POST[‘submit’])){

 

//This input will hold either the username or email address of the person trying to login. Once again, we MUST use mysqli_real_escape_string() to protect our site from MySQL injections.

$usernameoremail = mysqli_real_escape_string($conn, $_POST[‘usernameoremail’]);

 

//The user’s password.

$password = mysqli_real_escape_string($conn, $_POST[‘password’]);

        

         //Check whether or not the user entered a username or email address.

if(strlen($usernameoremail) < 1){

echo “Please enter your username or email address.”; //Error message.

echo “<br><br><a href=’login.php’>Return To Login</a>”; //Return to the login page with this link.

exit(); //Exit the script.
}

        

         //Check if a password was provided.

if(strlen($password) < 1){

echo “Please enter your password.”; ///Error message.

echo “<br><br><a href=’login.php’>Return To Login</a>”; //Return link.
}

        

         //We store the MySQL command in this string. We’ll use it next.

$sql = “SELECT username, password FROM users WHERE username=’$usernameoremail’ AND password=’$password_crypt’ OR email=’$usernameoremail’ AND password=’$password_crypt’”;      

 

//We execute the database query with our connection and command variables.

$query = mysqli_query($conn, $sql);

 

//Here we check whether or not the query returned any values. We do this using the “mysqli_num_rows()” method. This function returns an integer representing the total number of rows retrieved by a MySQL query. If the query finds an account with the username and password provided, then it will return a value one and we will know that the person’s account exists and that they entered the correct login information. If this is the case, then we set two browser cookies to log the user into his or her account.

if(mysqli_num_rows($query) > 0){

   

/*Here we gather the member’s username and password directly from the database. We do this because we don’t know whether the username or email address was used to login. This means that we can’t use the “$usernameoremail” variable. It’s also nice to ensure that the information stored in the cookies is 100% accurate since it’s coming directly from the database.

 

We collect the username and password from the database via our query and place it into an array called “$row”. We then separate the array into two variables so we have access to both the username and password.*/

$row = mysqli_fetch_array($query);

         $user_username = $row[‘username’];

         $user_password = $row[‘password’];

   

//We set our cookies with four parameters: the name of the cookie, the information it holds, the time until expiration (one day in seconds), and the directory it is allowed to affect (we set this to “/” which means the root directory).

$username_cookie = set_cookie(CB_Username”, $user_username, time() + 86400, “/”); //This cookie holds the member’s username.

$password_cookie = set_cookie(CB_Password”, $user_password, time() + 86400, “/”); //This cookie holds their password.

 

//If the two cookies are created in the user’s browser successfully then we redirect them to their profile page using the “header()” function. Otherwise, we echo an error message and then provide a return link.

if($username_cookie and $password_cookie){

    header(“location: profile.php”);

} else {

    echo “Sorry, we were unable to log into your account successfully.”;

echo “<br><br><a href=’login.php’>Return To Login</a>”;

}
} else {

//If “mysqli_num_rows()” did not find more than zero matching rows, then we know that the login information provided was not correct.

echo “Your username or password was incorrect.”;

echo “<br><br><a href=’login.php’>Return To Login</a>”;
}


}

 

//Close the connection.

mysqli_close($conn);

 

?>

 

 

The clean code:

 

 

<?php

   

    include_once(conn.php”);

 

if(isset($_POST[‘submit’])){

 

$usernameoremail = mysqli_real_escape_string($conn, $_POST[‘usernameoremail’]);

$password = mysqli_real_escape_string($conn, $_POST[‘password’]);

        

if(strlen($usernameoremail) < 1){

echo “Please enter your username or email address.”;

echo “<br><br><a href=’login.php’>Return To Login</a>”;

exit();
}

        

if(strlen($password) < 1){

echo “Please enter your password.”;

echo “<br><br><a href=’login.php’>Return To Login</a>”;
}

        

$sql = “SELECT username, password FROM users WHERE username=’$usernameoremail’ AND password=’$password_crypt’ OR email=’$usernameoremail’ AND password=’$password_crypt’”;

$query = mysqli_query($conn, $sql);

if(mysqli_num_rows($query) > 0){  

$row = mysqli_fetch_array($query);

         $user_username = $row[‘username’];

         $user_password = $row[‘password’];

   

$username_cookie = set_cookie(CB_Username”, $user_username, time() + 86400, “/”);

$password_cookie = set_cookie(CB_Password”, $user_password, time() + 86400, “/”);

 

if($username_cookie and $password_cookie){

    header(“location: profile.php”);

} else {

    echo “Sorry, we were unable to log into your account successfully.”;

echo “<br><br><a href=’login.php’>Return To Login</a>”;

}
} else {

echo “Your username or password was incorrect.”;

echo “<br><br><a href=’login.php’>Return To Login</a>”;
}


}

 

mysqli_close($conn);

 

?>

 

 

Next we add a few things to the profile page to make it dynamic.

 

 

 

 

 

Making the Profile Page Dynamic

 

Open “profile.php” which should currently contain the following code…

 

 

<!DOCTYPE html>

 

<html>

<head>

<title>(username) | Profile</title>

</head>

<body>

    <h1>Your Profile</h1>

    <br>

    <div>Hello there <b>(username here)</b>, welcome to your profile page!</div>

    <br><br>

    <div>Your email address is <b>(email here)</b>.</div>

</body>

</html>

 

 

Now, before we can use any dynamic variables we need to add a bit of PHP at the top of the page to gather that information. After adding that, we adjust the HTML document a bit to change the static values to dynamic variables.

 

 

<?php

 

include_once(conn.php”); //Initiate connection.

 

$login_status = “off”; //Create a variable representing the user’s login status and give it a default value of ‘off’.

 

//If the two login cookies are set then we place their values into variables, run a query to fetch the user’s email address, then set the $login_status variable to ‘true’.

if(isset($_COOKIE[‘CB_Username’]) and isset($_COOKIE[‘CB_Password’])){

$u_username = $_COOKIE[CB_Username’];

$u_password = $_COOKIE[CB_Password’];

 

$sql = “SELECT email FROM users WHERE username=’$u_username’ AND password=’$u_password’”; //MySQL command.

$query = mysqli_query($conn, $sql); //MySQL query.

if(mysqli_num_rows($query) > 0){ //Check if the username and password are valid.

    $row = mysqli_fetch_array($query);

         $u_email = $row[‘email’];

 

$login_status = “on”;

}
}

 

//If the two login cookies were not set or their values were invalid, then the “$login_status” variable will remain ‘off’. In that case, we’ll header the user away from the profile back and back to the login page since they shouldn’t be able to access their profile unless logged in.

    if($login_status == “off”){

         header(“location: login.php”);

         exit();

}

 

?>

 

<!DOCTYPE html>

 

<html>

<head>

    <!-- Here we create a PHP block and use it to echo out the “$u_username” variable we created above. -->

<title><?php echo $u_username; ?> | Profile</title>

</head>

<body>

    <h1>Your Profile</h1>

    <br>

    <!-- We echo out the username onto the user’s profile page. -->

    <div>Hello there <b><?php echo $u_username; ?></b>, welcome to your profile page!</div>

    <br><br>

    <!-- The user’s email address is displayed here. -->

    <div>Your email address is <b><?php echo $u_email; ?></b>.</div>

</body>

</html>

 

 

Below is the code without comments or highlights…

 

 

<?php

 

include_once(conn.php”);

 

$login_status = “off”;

 

if(isset($_COOKIE[‘CB_Username’]) and isset($_COOKIE[‘CB_Password’])){

$u_username = $_COOKIE[CB_Username’];

$u_password = $_COOKIE[CB_Password’];

 

$sql = “SELECT email FROM users WHERE username=’$u_username’ AND password=’$u_password’”;

$query = mysqli_query($conn, $sql);

if(mysqli_num_rows($query) > 0){

    $row = mysqli_fetch_array($query);

         $u_email = $row[‘email’];

 

$login_status = “on”;

}
}

 

    if($login_status == “off”){

         header(“location: login.php”);

         exit();

}

 

?>

 

<!DOCTYPE html>

 

<html>

<head>

<title><?php echo $u_username; ?> | Profile</title>

</head>

<body>

    <h1>Your Profile</h1>

    <br>

    <div>Hello there <b><?php echo $u_username; ?></b>, welcome to your profile page!</div>

    <br><br>

    <div>Your email address is <b><?php echo $u_email; ?></b>.</div>

</body>

</html>

 

 

Save file changes and then move on to the final step of development...

 

 

 

 

Creating the Logout Script

 

The logout script will be incredibly simply. To log a user into their account, we created two cookies containing their username and encrypted password. If those cookies were set in the browser while viewing the profile page, then we could use them to extract that user’s account information from the database and display it on profile page wherever we wanted. So logically, if we want to log a person out of their account, then all we need to do is remove the two cookies that were set during login. To do that we simply re-set the same two cookies, while changing the expiration date to a negative value. In the code below we set the expiration time to one hour ago. This means that the browser will delete the cookie as soon as it is set which will accomplish our task to logging the user out of their account. Create a new file named “logout.php” and save it in your root directory. Write the following code into the file...

 

 

<?php

 

//Recreate the username and password cookies with the same exact names as before with the expiration set to ‘current time minus one hour’ and the path set to forward slash which means the root directory.

$CB_Username = set_cookie(CB_Username”, time() – 3600, “/”);

$CB_Password = set_cookie(CB_Password”, time() – 3600, “/”);

 

//If the username and password cookies are set successfully then it means that we’ve been logged out successfully and we’ll be redirected to the login page. Otherwise, we must have run into some sort of problem and will print an error message to the user.

if($CB_Username and $CB_Password){

    header(“location: login.php”);

} else {

    echo “Sorry, we were unable to log out of your account.”;

}

 

?>

 

 

Clean code...

 

 

<?php

 

$CB_Username = set_cookie(CB_Username”, time() – 3600, “/”);

$CB_Password = set_cookie(CB_Password”, time() – 3600, “/”);

 

if($CB_Username and $CB_Password){

    header(“location: login.php”);

} else {

    echo “Sorry, we were unable to log out of your account.”;

}

 

?>

 

 

 

 

Summary

 

That’s it! After saving the “logout.php” file changes navigate to “register.php” on your site. Fill out the form and click “Create New Account”. Your account will then be created inside MySQL. You will then be redirected to the login page. Enter your account information and then click “Login”. You should then be taken to your profile page where your basic account info is displayed. To complete the final step of testing, click the logout button and you should be sent back to the original login page. If you try to navigate to “profile.php” now, you will simply be redirected to the login page since the profile page can only be viewed while logged.

 

Hurray! Great job on completing your first basic user login system. You can now take this knowledge and use it to create your own projects and make your own ideas a reality!

 

If you have any questions, comments, or ideas then don’t hesitate to leave a post down below and I’ll do my best to respond promptly.

 

Cheers!