Create Login System using PHP and MySQL DB


0

In this article, we will discuss how to create a Login System using PHP and MySQL.

Before generating the login system first, we must need to know about the pre-requisites to generate the login module.

Pre-requisites

  • HTML, CSS, PHP, and MySQL basics
  • Code Editor – For writing the code – visual studio code, Notepad, Notepad++, sublime, etc.
  • XAMPP – XAMPP is a cross-platform server, which stands for Cross-platform(X) Apache server (A), MySQL (M), PHP (P), Perl (P).


Create Project folder


Let’s generate a project folder named “login-system-php-mysql”.

Within “login-system-php-mysql” folder, we are going to generate files which required to build the Login system.

SQL Script

Use the following 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 store info for MySQL Database configuration.

PHP script to create a MySQL DB connection:

<?php

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

$db_name = "login_system";

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

if (!$conn) {
	echo "Connection failed!";
}

Mark that we ate connecting our MySQL server DB using PHP mysqli_connect() function which accept 4 arguments, i.e. our “host”, “username”, “password” and “Db name”.

After that, we have successfully connected to our DB, further, we will generate the login form.

Create index.php file

In this step, we need to make the login form using html for the website user to interface with it. Let’s generate an index.php file with the given below 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>

Notice that in the above code, we have to put style.css so we will generate a style.css file.

Create style.php file

After that, we will generate a style.css file to give a more beautiful view to the login form. The CSS code for the style.css file is following 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

In this step, we will add the logic to authentication username and password with MySQL DB user and password. Let’s make a login.php with the given 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 redirect to 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

On this page Users can also click on the Logout button to log out from the webpage. Let’s generate logout.php file with the given code into it:

<?php 
session_start();

session_unset();
session_destroy();

header("Location: index.php");

Running Login system application

To execute the login application, start the XAMPP and run the apache server and Mysql.

Aster that, type localhost/directory name/file name (localhost/login-system-php-mysql/index.php) in the browser url and press Enter key.

Demo

All system is done now. Enter the username and password to the login form and click the login button.

create-login-system-with-php-and-mysql

After Login:


Like it? Share with your friends!

0
Developer

0 Comments