How to Create Secure Login System With PHP And MySQL
- Article
- Comment
Introduction
How to Create Secure Login System With PHP And MySQL. Secure PHP Login Script With Downloadable Source code. An Advanced Login Script requires to keep the system maintained safely. With Help of PHP and MySQL, we have lot of doubts and bugs to provide a better login system. Here I am going to make you a secure login system. For the secure login system, We need to register form and login form. Both forms will be designed first.
Pre-requirements
- HTML form for Login & Registration
- Index page with logout button after login success
- MySQL Query
- PHP Code snippet for Login Success
Let’s Prepare the HTML form and Index Pages. I have a login page which designed already its available here. And the dashboard Design will be here with simple thing.
MySQL query for users table, the below query helps to create a users table for it.
CREATE TABLE IF NOT EXISTS `kv_users` ( `id` int(10) NOT NULL AUTO_INCREMENT, `full_name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And now, let’s create a dashboard page with neat look and you can show it after successful login. Let’s write some functions where are necessary to use in our login system. Let’s start with database connectivity.
Db Connectivity
Let’s connect the database with our connectivity code and also include the config.php
to get db configuration credentials.
require_once("../config.php"); global $db; $db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME); if(!$db){ die( "Sorry! There seems to be a problem connecting to our database."); }
Register
Let’s register the user with help of below function. From the form of registration, we will send data to this function to register user and create access to him.
function register($full_name, $user, $pass, $emailId){ global $db; $full_name = mysqli_real_escape_string($db, $full_name); $username = mysqli_real_escape_string($db, $user); $password = mysqli_real_escape_string($db, $pass); $email = mysqli_real_escape_string($db, $emailId); $wp_hasher = new PasswordHash(16, true); $pass = $wp_hasher->HashPassword( trim( $password ) ); $sql = "INSERT INTO kv_users (full_name, email,password,username) VALUES ('".$full_name."', '".$email."', '".$pass."', '".$username."') "; $result = mysqli_query($db, $sql); return mysqli_insert_id($db); }
Here you might notice something different in this system. PasswordHash
is a class which helps to create secured password with help of your entered key. Let’s use it and you can get it finally from the downloadable thing below.
Login
Let’s have a form to get user access credentials such username and password to the system to check whether the user is right or wrong.
function login($user, $pass){ global $db; $username = mysqli_real_escape_string($db, $user); $password = mysqli_real_escape_string($db, $pass); $sql = "SELECT id, password FROM kv_users WHERE username='".$username."' LIMIT 1 "; $result = mysqli_query($db, $sql); $id = mysqli_fetch_row($result); if($id){ $password_hashed = $id[1]; $wp_hasher = new PasswordHash(16, true); if($wp_hasher->CheckPassword($password, $password_hashed)) { return $id[0]; } } else { return false; } }
Also we need logout feature to exit from the system.
Logout
To exit from the system
function logout(){ unset($_SESSION['user_id']); session_destroy(); header('Location: index.php'); exit(); }
Username Check
Let’s validate the username before saving it to the database.
function usernameExist($user){ global $db; $username = mysqli_real_escape_string($db, $user); $sql = "SELECT id FROM kv_users WHERE username='".$username."' LIMIT 1 "; $result = mysqli_query($db, $sql); $id = mysqli_fetch_row($result); return ($id[0] > 0); } }
Now, Let’s make the login Registration form.
Registration Form
<form action="" method="post" > <?php if(!empty($reg_errors)) { echo '<div class="error">'; foreach ($register_errors as $error) { echo '<p>'.$error.'</p>'; } echo '</div>'; } ?> <div class="group"> <input type="text" name="full_name" ><span class="highlight"></span><span class="bar"></span> <label>Full name</label> </div> <div class="group"> <input type="email" name="email" ><span class="highlight"></span><span class="bar"></span> <label>Email</label> </div> <div class="group"> <input type="text" name="username" ><span class="highlight"></span><span class="bar"></span> <label>Username</label> </div> <div class="group"> <input type="text" name="password" ><span class="highlight"></span><span class="bar"></span> <label>Password</label> </div> <input type="hidden" name="register" value="yes" > <button type="submit" class="buttonui "> <span> Register </span> <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div> </button> <a class="buttonui " href="login.php?action=login" style="line-height:4em; text-decoration: none; padding:2%" > <span> Login Back </span> <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div></a> </form>
The below PHP code helps to handle the form and send data to registration function to store the details.
$register_errors= $login_error = array(); if('POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['register'])) { $fields = array( 'full_name', 'username', 'email', 'password' ); foreach ($fields as $field) { if (isset($_POST[$field])) $posted[$field] = stripslashes(trim($_POST[$field])); else $posted[$field] = ''; } if ($posted['full_name'] == null) array_push($register_errors, sprintf('<strong>Notice</strong>: Please enter the User Full Name.', 'neem')); if ($posted['email'] == null) array_push($register_errors, sprintf('<strong>Notice</strong>: Please enter the User Email.', 'neem')); if ($posted['password'] == null) array_push($register_errors, sprintf('<strong>Notice</strong>: Please enter the User Password.', 'neem')); if ($posted['username'] == null ) array_push($register_errors, sprintf('<strong>Notice</strong>: Please enter the User Username.', 'neem')); if(usernameExist($posted['username'])){ array_push($register_errors, sprintf('<strong>Notice</strong>: The Entered Username Already Exist.', 'neem')); } $reg_errors = array_filter($register_errors); if (empty($reg_errors)) { //Check whether everything entered to create new user. register($posted['full_name'], $posted['username'], $posted['password'], $posted['email']); } }
Let’s Create the Login form and its php code to handle it.
Login Form
Login form html code helps to get the details from users to validate access.
<form action="" method="post" > <?php if(!empty($log_error) || (isset($mismatchErr) && $mismatchErr != '')) { echo '<div class="error">'; foreach ($login_error as $error) { echo '<p>'.$error.'</p>'; } echo $mismatchErr.'</div>'; } ?> <div class="group"> <input type="text" class="used" name="username" ><span class="highlight"></span><span class="bar"></span> <label>Username</label> </div> <div class="group"> <input type="password" name="password" ><span class="highlight"></span><span class="bar"></span> <label>Password</label> </div> <input type="hidden" name="login" value="yes" > <button type="submit" class="buttonui "> <span> Login </span> <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div> </button> <a class="buttonui " href="login.php?action=register" style="line-height:4em; text-decoration: none; padding:2%" > <span> Register </span> <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div></a> </form>
And the next thing will be the php code to handle the form data and check login access.
if('POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['login'])) { $username = stripslashes(trim($_POST['username'])); $password = stripslashes(trim($_POST['password'])); $mismatchErr = ''; if ($password == null ) array_push($login_error, sprintf('<strong>Notice</strong>: Please enter the User Password.', 'neem')); if ($username == null ) array_push($login_error, sprintf('<strong>Notice</strong>: Please enter the User Username.', 'neem')); $log_error = array_filter($login_error); if (empty($log_error)) { //Check whether everything entered to create new user. $loginn = login($username, $password); if($loginn){ $_SESSION['user_id'] = $loginn; header('Location: index.php'); exit(); }else { $mismatchErr .= sprintf('<p> <strong>Notice</strong>: Please enter Valid Credentials. </p>', 'neem'); } } }
That’s it. You can get the downloadable zip with source code for testing. If you are interested to read more articles from me and want to follow me on social sites to get in touch with me, just follow up with links and also if you wish to write me the doubts and further clarifications write me your comments on next tab.