Secure Login and Registration in PHP using Prepared Statements Tutorial
Introduction
In this tutorial, you will learn the basics and best practices to create a Secure Login and Registration in PHP. This tutorial provides sample snippets that demonstrate a secure login and registration feature in PHP using Prepared Statements. The main goal of this article is to provide the students or those programmers who are new to PHP Language a reference to learn with.
Why do we need to secure our Web Application Login and Registration?
We must secure our site's login and registration feature and functionality to prevent malicious hackers to ruin or get access to our site's data. Doing so, your end-users will trust also your site for using it because it protects their data especially if they are storing sensible or personal data and information on your site.
How can we Create a Secure Login and Registration using PHP?
There are a lot of ways and techniques to create a secure login and registration feature for sites. One of the most common nowadays is, developers create a 2 Factor Authentication or oAuth, Here, I will only show you or teach you the best practice to create a basic one using the PHP Prepared Statements and sanitizing the data.
Getting Started
Kindly download a virtual server software such as the XAMPP/WAMP on your local machine to run our PHP scripts and for the MySQL Database. After successful installation of the software make sure that your Apache and MySQL are already started or running on your local machine.
Creating the Database
Create a new database and name it "sample_db". If you are using XAMPP/WAMP, browse http://localhost/phpmyadmin in your preferred browser to create a database. After that run or execute the following MySQL Script to create the `users` table in your newly created database.
- CREATE TABLE `user_tbl` (
- `first_name` varchar(250) NOT NULL,
- `middle_name` varchar(250) NOT NULL,
- `last_name` varchar(250) NOT NULL,
- `username` text NOT NULL,
- `password` text NOT NULL
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Creating the Database Connection
The following snippet is the PHP Script that connects your site to the database. Save the script as "db-connect.php" in your source code folder.
- <?php
- // Server Name
- $host = "localhost";
- // Database Username
- $username = "root";
- // Database Password
- $password = "";
- // Database Name
- $db_name = "sample_db";
- // Create Connection
- $conn = new mysqli($host, $username, $password, $db_name);
- // Check if database connection failed then do die
- if(!$conn){
- }
- ?>
Creating the Authentication
The following snippet is a PHP script that contains the code to authenticate the user if he/she is allowed to load the current page. This code prevents the users to access the main page without logging in to the site. Save the script as "auth.php".
- <?php
- $_self = $_SERVER['PHP_SELF'];
- // Check if page is in login or registration page
- }
- }else{
- // Check if not in login or registration page
- }
- }
- ?>
Creating the Registration
Here is the sample snippet for creating a Registration Page for your site. It contains HTML and PHP Scripts for the page interface and the registration form of the site. This file also contains the code for processing or saving the new user information to the database. Save the file as "register.php"
- <?php
- include "db-connect.php";
- require_once("auth.php");
- if($_SERVER['REQUEST_METHOD'] == "POST"){
- $fname = addslashes($conn->real_escape_string($_POST['first_name']));
- $mname = addslashes($conn->real_escape_string($_POST['middle_name']));
- $lname = addslashes($conn->real_escape_string($_POST['last_name']));
- $uname = addslashes($conn->real_escape_string($_POST['username']));
- $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
- // Check username duplication
- $check = $conn->query("SELECT id FROM `user_tbl` where `username` = '{$uname}'")->num_rows;
- if($check > 0){
- $err = "Username is already taken!";
- }else{
- $sql = "INSERT INTO `user_tbl` (`first_name`, `middle_name`, `last_name`, `username`, `password`) VALUES (?, ?, ?, ?, ?)";
- $stmt = $conn->prepare($sql);
- $stmt->bind_param("sssss", $fname, $mname, $lname, $uname, $password);
- $stmt->execute();
- if($stmt->affected_rows > 0){
- $_SESSION['success_msg'] = $success;
- header('location: register.php');
- unset($_POST);
- exit;
- }else{
- $err = "Creating your account has been failed for some reason!";
- }
- }
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
- <style>
- html, body {
- min-height:100%;
- width: 100%
- }
- </style>
- </head>
- <body class="bg-primary bg-opcaity-75 bg-gradient">
- <div class="container my-5 py-4">
- <div class="col-lg-5 mx-auto">
- <hr class="border-light" height="2px">
- <div class="card rounded-0">
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form id="registration-form" action="" method="POST">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="first_name" name="first_name" required="required" value="<?= isset($_POST['first_name']) ? $_POST['first_name'] : '' ?>" placeholder="John">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="middle_name" name="middle_name" value="<?= isset($_POST['middle_name']) ? $_POST['middle_name'] : '' ?>" placeholder="(optional))">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="last_name" name="last_name" required="required" value="<?= isset($_POST['last_name']) ? $_POST['last_name'] : '' ?>" placeholder="Smith">
- </div>
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="username" name="username" required="required" value="<?= isset($_POST['username']) ? $_POST['username'] : '' ?>" placeholder="myusername">
- </div>
- <div class="mb-3">
- <input type="password" class="form-control rounded-0" id="password" name="password" required="required" placeholder="********">
- </div>
- <?php if(isset($_SESSION['success_msg']) && !empty($_SESSION['success_msg'])): ?>
- <div class="alert alert-success">
- <?= $_SESSION['success_msg'] ?>
- </div>
- <?php unset($_SESSION['success_msg']); ?>
- <?php else: ?>
- <p class="text-center">
- </p>
- <?php endif; ?>
- <?php if(isset($err) && !empty($err)): ?>
- <div class="alert alert-danger">
- <?= $err ?>
- </div>
- <?php endif; ?>
- </form>
- </div>
- </div>
- <div class="card-footer text-center">
- </div>
- </div>
- </div>
- </div>
- <?php
- $conn->close();
- ?>
- </body>
- </html>
Result
Creating the Login
The next snippet is the Login Page scripts that consist also of HTML and PHP Scripts. It contains the elements of the page interface of the login form. Save the file as "login.php".
- <?php
- include "db-connect.php";
- require_once("auth.php");
- // Process Login
- if($_SERVER['REQUEST_METHOD'] == "POST"){
- // username
- $uname = addslashes($conn->real_escape_string($_POST['username']));
- // Check user if Exist
- $sql = "SELECT * FROM `user_tbl` where `username` = ?";
- $stmt = $conn->prepare($sql);
- $stmt->bind_param("s", $uname);
- $stmt->execute();
- $result = $stmt->get_result();
- if($result->num_rows > 0){
- // If user data exist
- $details = $result->fetch_assoc();
- // verify given password
- $password_verify = password_verify($_POST['password'], $details['password']);
- if($password_verify){
- // Save user details on session
- foreach($details as $k => $v){
- $_SESSION[$k] = $v;
- }
- header('location: index.php');
- }else{
- // If Password does not match
- $err = "Invalid match of username and password.";
- }
- }else{
- // If User details does not exist
- $err = "Invalid username.";
- }
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
- <style>
- html, body{
- height:100%;
- width:100%;
- margin:unset;
- }
- </style>
- </head>
- <body class="bg-primary bg-opcaity-75 bg-gradient">
- <div class="container my-auto d-flex flex-column align-items-center justify-content-center h-100">
- <hr>
- <div class="col-lg-5 mx-auto">
- <div class="card rounded-0">
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <form id="login-form" action="" method="POST">
- <div class="mb-3">
- <input type="text" class="form-control rounded-0" id="username" name="username" required="required" value="<?= isset($_POST['username']) ? $_POST['username'] : '' ?>" placeholder="myusername">
- </div>
- <div class="mb-3">
- <input type="password" class="form-control rounded-0" id="password" name="password" required="required" placeholder="********">
- </div>
- <?php if(isset($err) && !empty($err)): ?>
- <div class="alert alert-danger">
- <?= $err ?>
- </div>
- <?php endif; ?>
- <p class="text-center">
- </p>
- </form>
- </div>
- </div>
- <div class="card-footer text-center">
- </div>
- </div>
- </div>
- </div>
- <?php
- $conn->close();
- ?>
- </body>
- </html>
Result
Creating the Main Page
Here's a sample snippet of the main page for the logged-in users. The page displays the information of the user except for the password. Save the file as "index.php".
- <?php
- include "db-connect.php";
- require_once("auth.php");
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
- <style>
- html, body{
- height:100%;
- width:100%;
- margin:unset;
- }
- </style>
- </head>
- <body class="bg-primary bg-opcaity-75 bg-gradient">
- <div class="container h-100 d-flex flex-column align-items-center justify-content-center">
- <div class="col-6 mb-3">
- <hr class="border-light">
- </div>
- <div class="col-lg-5">
- <div class="card rounded-0">
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <hr>
- <dl>
- </dl>
- </div>
- <div class="d-grid mt-3">
- </div>
- </div>
- </div>
- </div>
- </div>
- <?php
- $conn->close();
- ?>
- </body>
- </html>
Result
Creating the Logout Script
Here's the snippet for destroying the session of the logged-in user. It is a PHP Script that unsets or destroys the current user session. Save the file as "logout.php".
- <?php
- ?>
DEMO VIDEO
That's it! You can now test the sample application that demonstrates our goal for this tutorial which is a site that contains a secure login and registration feature. If you found or encountered any errors on your end, please review you changes or modifications you've made and try to differentiate them from the codes I provided above. You can also download the working source code I created for this tutorial. The download button is located below this article.
That is the end of this tutorial. I hope this will help you with what you are looking for and that you'll find this useful for your future PHP Projects. Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding :)
Add new comment
- 2205 views