Login System with PHP and MySQL Database

In this tutorial, we will learn how to build a Login System using PHP and the MySQL database.

Before creating the login system first, we need to know about the pre-requisites to create the login module.

Pre-requisites

  • HTML, CSS, PHP, and MySQL basics
  • Text Editor - For writing the code - Notepad, Notepad++, Dreamweaver, etc.
  • XAMPP - XAMPP is a cross-platform software, which stands for Cross-platform(X) Apache server (A), MySQL (M), PHP (P), Perl (P). XAMPP is a complete software package, so, we don't need to install all these separately.

Create Project Directory

Let's create a project directory named "login-system-php-mysql".

Within "login-system-php-mysql" directory, we are going to create files required to build the Login system.

SQL Script

Use the below SQL script to create a database and table:
CREATE DATABASE login_system;

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `users` (`id`, `user_name`, `password`, `name`) VALUES
(1, 'admin', '123', 'admin'),
(2, 'john', 'abc', 'John');

Create db_config file

Let's create a db_config file that contains information about MySQL Database configuration.

PHP code to create a MySQL database connection:
<?php

$host= "localhost";
$username= "root";
$password = "";

$db_name = "login_system";

$conn = mysqli_connect($host, $username, $password, $db_name);

if (!$conn) {
	echo "Connection failed!";
}
Note that we ate connecting our MySQL server Database using PHP mysqli_connect() function which takes four arguments, i.e. our “host”, “username”, “password” and “database”.

Now, we have successfully connected to our Database, in the next step, we will create the login form.

Create index.php file

First, we need to design the login form for the website user to interact with it. Let's create an index.php file with the following code into it:
<!DOCTYPE html>
<html>
<head>
	<title>LOGIN System</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
     <form action="login.php" method="post">
     	<h2>Login System</h2>
     	<?php if (isset($_GET['error'])) { ?>
     		<p class="error"><?php echo $_GET['error']; ?></p>
     	<?php } ?>
     	<label>User Name :</label>
     	<input type="text" name="uname" placeholder="User Name"><br>

     	<label>Password :</label>
     	<input type="password" name="password" placeholder="Password"><br>

     	<button type="submit">Login</button>
     </form>
</body>
</html>

Note that in the above file, we have added style.css so we will create a style.css file in the next step.

Create style.php file

Now, we will create a style.css file to provide a more attractive view to the login form. The CSS code for the style.css file is given below:

body {
	background: #1690A7;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	flex-direction: column;
}

*{
	font-family: sans-serif;
	box-sizing: border-box;
}

form {
	width: 500px;
	border: 2px solid #ccc;
	padding: 30px;
	background: #fff;
	border-radius: 15px;
}

h2 {
	text-align: center;
	margin-bottom: 40px;
}

input {
	display: block;
	border: 2px solid #ccc;
	width: 95%;
	padding: 10px;
	margin: 10px auto;
	border-radius: 5px;
}
label {
	color: #888;
	font-size: 18px;
	padding: 10px;
}

button {
	float: right;
	background: #555;
	padding: 10px 15px;
	color: #fff;
	border-radius: 5px;
	margin-right: 10px;
	border: none;
}
button:hover{
	opacity: .7;
}
.error {
   background: #F2DEDE;
   color: #A94442;
   padding: 10px;
   width: 95%;
   border-radius: 5px;
   margin: 20px auto;
}

h1 {
	text-align: center;
	color: #fff;
}

a {
	float: right;
	background: #555;
	padding: 10px 15px;
	color: #fff;
	border-radius: 5px;
	margin-right: 10px;
	border: none;
	text-decoration: none;
}
a:hover{
	opacity: .7;
}

Create login.php file

Now, we will write the logic to authenticate username and password with MySQL database username and password. Let's create a login.php with the following content into it:
<?php 
session_start(); 
include "db_conn.php";

if (isset($_POST['uname']) && isset($_POST['password'])) {

	function validate($data){
       $data = trim($data);
	   $data = stripslashes($data);
	   $data = htmlspecialchars($data);
	   return $data;
	}

	$uname = validate($_POST['uname']);
	$pass = validate($_POST['password']);

	if (empty($uname)) {
		header("Location: index.php?error=User Name is required");
	    exit();
	}else if(empty($pass)){
        header("Location: index.php?error=Password is required");
	    exit();
	}else{
		$sql = "SELECT * FROM users WHERE user_name='$uname' AND password='$pass'";

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

		if (mysqli_num_rows($result) === 1) {
			$row = mysqli_fetch_assoc($result);
            if ($row['user_name'] === $uname && $row['password'] === $pass) {
            	$_SESSION['user_name'] = $row['user_name'];
            	$_SESSION['name'] = $row['name'];
            	$_SESSION['id'] = $row['id'];
            	header("Location: home.php");
		        exit();
            }else{
				header("Location: index.php?error=Incorect User name or password");
		        exit();
			}
		}else{
			header("Location: index.php?error=Incorect User name or password");
	        exit();
		}
	}
	
}else{
	header("Location: index.php");
	exit();
}

Create home.php file

After successful login, it will display the home page:
<?php 
session_start();

if (isset($_SESSION['id']) && isset($_SESSION['user_name'])) {

 ?>
<!DOCTYPE html>
<html>
<head>
	<title>HOME</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
     <h1>Hello, <?php echo $_SESSION['name']; ?></h1>
     <a href="logout.php">Logout</a>
</body>
</html>

<?php 
}else{
     header("Location: index.php");
     exit();
}
 ?>

Create logout.php file

Users can click on the Logout button to log out from the application. Let's create logout.php file with the following content into it:
<?php 
session_start();

session_unset();
session_destroy();

header("Location: index.php");

Running Login system application

To run the login system application, open the XAMPP control panel and run the apache server and PHP.

Now, type localhost/folder name/file name (localhost/login-system-php-mysql/index.php) in the browser and press Enter key.

Demo

All setup is done now.  Enter the username and password in the login form and click the login button.

After Login:

Source code on GitHub

The source code of this tutorial is hosted on our GitHub repository at https://github.com/sourcecodeexamples/login-system-php-mysql

Comments