How to create secure login using php and mysql

In this tutorial we are going to implement the most secure login system using php and mysql, every projects login is mostly require part of system. so, let’s have begin with creating sql table.

Create SQL table

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email_address` varchar(255) NOT NULL,
  `user_role` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT

after creating table insert one user record in table which require to compare data from front-end.

INSERT INTO `users` (`id`, `username`, `password`, `email_address`, `user_role`) VALUES
(1, 'admin@gmail.com', '$2y$04$x.Leg9GtLYPmw0G7rZZZj.ARrhblZxVR7W33cmhqW316F2iLKMz1.', 'admin@gmail.com', 'ADMIN');

Create index.php

<?php include('config.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
	
	<style>
	.account-col {
		width: 300px;
		margin: 0 auto;
		text-align: center;
	}
	</style>
	
	<link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/jquery.dataTables.min.css" crossorigin="anonymous">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
	<script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js" crossorigin="anonymous"></script>
	
	
</head>
<body>
		
        <div class="container">
			<div class="row">
                <div class="account-col text-center">
                    
                    <h3>Log into your account</h3>
                    <form class="m-t" role="form" method="post" action="login.php">
						<div class="form-group login-input">
							<span style="color: #b70a0a;"><?php if(isset($_GET['invalid'])){ echo "Your Email or Password is invalid"; } ?></span>
						</div>
						
                         <div class="form-group">
                            <input type="text" class="form-control" name="email" placeholder="Email" required="">
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-control"  name="password" placeholder="Passowrd" required="">
                        </div>
                        <button type="submit" class="btn btn-primary btn-block ">Login</button>
                
                     </form>
                </div>
            </div>
			
		</div>
    
</body>
</html>

Create login.php file we implement all logic there.

Create login.php

<?php
	include('config.php');
	if($_SERVER["REQUEST_METHOD"] == "POST") {
		$myemail	= mysqli_real_escape_string($conn,$_POST['email']);
		$mypassword = mysqli_real_escape_string($conn, $_POST["password"]);
		$sql = "SELECT * FROM users WHERE username = '$myemail' LIMIT 1";
		$result = mysqli_query($conn,$sql);
		
		$count = mysqli_num_rows($result);
		  
		if($count == 1) {
			
			$row = mysqli_fetch_array($result);
				
			if(password_verify($mypassword, $row["password"]))  {
				  
				$arr=array('id'=>$row['id'], 'username'=>$row['username'],'user_role'=>$row['user_role']);
				 
				$_SESSION= $arr;
				
					header("location:redirect.php");
					exit;
					
				}
			
		} else {
				header("location:index.php?invalid=1");
				exit;
		}
	}
?>

password_verify($mypassword, $row[“password”] which compare the password from user enter and DB if both are same then we can call redirect.php or you can change any file to after login otherwise when wrong username and password redirect same page index.php.

Create redirect.php

<?php
	include('config.php');
	if(isset($_SESSION['id'])){
?>
	Welcome, <?php echo $_SESSION['username'];  ?>
	<a href="logout.php">Logout</a>
			
<?php } ?>

After successfully login, user need to logout.php. so let’s create logout.php file

Create logout.php

<?php
include('config.php');
// Destroy the session:
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
header("location:index.php");
exit;
?>

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply