Login System using PHP with MySql Database Easy Steps

In this tutorial, you will learn how you can create your own login system using PHP, MySql, Session, HTML and CSS on which users can log in to the profile page and log out. This is a very basic but effective tutorial. Where I do not only focus what it gives but also focus on how it gives. After reading this post, I hope you will learn about HTML, PHP, MySql and also Session.

Complete Guide of Login System using PHP

Login form (index.php) 

<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php"); // Redirecting To Profile Page
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password"><br><br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</body>
</html>

The output of the above code

login formThis index.php is a default page and it contains an HTML login form.

Line 2include(‘login.php’); allow us to connect with a login.php file.

Line 3–5. If a user is already login then  isset($_SESSION['login_user']) become true then the user does not need to log in and we redirect the user to profile.php.

182021. In an input field, we use name=" " attribute which we later use in a server-side to grab the value of that input field.

Php code for login (login.php) 

<?php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "company");
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT username, password from login where username=? AND password=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row {
$_SESSION['login_user'] = $username; // Initializing Session
header("location: profile.php"); // Redirecting To Profile Page
}
mysqli_close($conn); // Closing Connection
}
?>

Here we start the code by starting the session.

3. We declare $error = ''; to store an error message.

4. By using isset($_POST['submit']) we check, did user click the submit button or not? If the submit button is not set then we do nothing.

5. We use empty($_POST['username']) || empty($_POST['password']) to check username and password are empty or not. If it is empty then we give an error message to the user. If not then we can continue our login process from an else statement.

10–11. We grab the username and password which is submitted by the user.

13. Make a database connection with this login system

15. The SQL query to see is this username and password exist in a database or not.

22–23. If exist, store the username in a session and then redirect the user to profile.php.

26. At last, close a database connection.

Php code for user session (session.php) 

<?php
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "company");
session_start();// Starting Session
// Storing Session
$user_check = $_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$query = "SELECT username from login where username = '$user_check'";
$ses_sql = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
?>

Php code for user profile (profile.php) 

<?php
include('session.php');
if(!isset($_SESSION['login_user'])){
header("location: index.php"); // Redirecting To Home Page
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout"><a href="logout.php">Log Out</a></b>
</div>
</body>
</html>

3–5. We check, did ‘login user’ session exist or not? If ‘login user’ did not exist then that means, a user did not login we redirect the user to the login page which is index.php.

15. We use <?php echo $login_session; ?> to display username in a profile page.

16. If a user clicks the logout link then they will redirect to the logout page.

Php code for logout (logout.php) 

<?php
session_start();
if(session_destroy()) // Destroying All Sessions {
header("Location: index.php"); // Redirecting To Home Page
}
?>

In this logout page, we simply destroy the session and redirect the user to the login page.

CSS code to give style on whole login system (style.css) 

/*----------------------------------------------
CSS Settings For HTML Div ExactCenter
------------------------------------------------*/
span {
color:red
}
h2

{
text-align:center;
border-radius:10px 10px 0 0;
margin:-10px -40px;
padding:15px
}
hr

{
border:0;
border-bottom:1px solid;
margin:10px -40px;
margin-bottom:30px
}
#login

{
margin: auto;
width:450px;
border-radius:10px;
border:2px solid #ccc;
padding:10px 40px 25px;
background-color:#b6e6ff;
}
input[type=text],input[type=password]

{
width:96.5%;
padding:10px;
margin-top:8px;
border:1px solid #ccc;
padding-left:5px;
font-size:20px;
}
input[type=submit]

{
width:100%;
background-color:#2f90ff;
color:#fff;
border:2px solid #white;
padding:10px;
font-size:20px;
cursor:pointer;
border-radius:5px;
}
#profile

{
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7
}
#logout

{
float:right;
padding:5px;
border:dashed 1px gray
}
a

{
text-decoration:none;
color:#6495ed
}
i

{
color:#6495ed
}

MySQL code for creating databases and table for login system

CREATE DATABASE company;

CREATE TABLE login(
id int(10) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
)

Execute this code and then create a database and table for this login system.

Twitter: https://twitter.com/CodeAndCoins
Google+ : https://goo.gl/7vjhrp
Facebook: https://www.facebook.com/CodeAndCoins
Blog: https://CodeAndCoins.blogspot.com

Share this Video and Subscribe to my channel

3.4 5 votes
Article Rating
Subscribe
Notify of
5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Agostino I
Agostino I
4 years ago

Thanks for this post

Flexx
Flexx
3 years ago

Logout page is not working for me I got not go to the index.php if I will logout I stay on logout.php what i’m doing wrong ??

Hamza Zahid
Hamza Zahid
Reply to  Flexx
3 years ago

Sydney
Sydney
Reply to  Flexx
3 years ago

I had the same issue. To solve it, I added the following line of code under line 2 of logout.php unset($_SESSION['login_user']); and changed the if statement to if(!isset($_SESSION["login_user"])){
header("location: index.php"); // Redirecting To Home Page
}
Hope this helps!

trackback
3 years ago

[…] Login System using PHP with MySql Database with Session … […]