Script for login logout and view using php mysql and bootstrap

In this tutorial, we are going to learn how to engender a secure PHP 7 utilizer authentication and authenticate system with MySQL database utilizing procedural programming approach. In the following demo, you can check out the final output of this PHP 7 Authenticate system tutorial.
Utilizer authentication is a standard security mechanism, It sanctions identified users to access any digital application or website. It rigorously obviates unidentified users from accessing web or mobile application.

We utilize digital products such as Facebook, Twitter, Gmail in our day to day life and we are virtually acclimated with utilizer registration and authenticate mechanism. You engender an account afore authenticate in to these applications this way you can utilize their features.

What We Will Learn:

In this article, we will highlight some of the core features that are required to build a complete login and registration system with PHP & MySQL.

  • Creating Signin and Signup forms with Bootstrap 4
  • Making MySQL database connection with PHP 7 project
  • Managing user data in session
  • PHP server-side validation
  • Handling error messages
  • Sending user verification email using SwiftMailer plugin
  • Securing a password with the password hash mechanism
  • Password verification
  • URL redirection based on user’s logged-in state
  • Display logged-in user’s data using PHP 7 session
  • Logout and destroying the session

Prerequisite

Before you start creating a secure PHP 7 Login & User Registration system, you must set up a local web server using MAMP or XAMPP.

PHP 7 File & Folder Structure

Open MAMP or XAMPP and start your web server then and go to htdocs folder and create the following folder and files which are essential to develop our user authentication system.

\-- php-user-authentication
  |-- config
      |--- db.php
  |-- controllers
      |--- login.php
      |--- register.php
      |--- user_activation.php
  |-- css
      |--- style.css
  |-- lib
      |--- 3rd party plugins
  |-- dashboard.php
  |-- header.php
  |-- index.php
  |-- logout.php
  |-- signup.php
  |-- user_verification.php

Create Database & Table in MySQL

Our local web server is up and running, go to <a href="http://localhost:8888/phpMyAdmin" rel="noopener noreferrer" target="_blank">PHPMyAdmin</a>.</p> <p>First create database&nbsp;<code>`your_database_name`</code>.</p> <p>Create table&nbsp;<code>`table_name`</code>&nbsp;in the MySQL database.</p> <p>You can create columns manually or even you can execute the below sql script from&nbsp;<code>SQL</code>&nbsp;tab to create columns with following values.</p> <pre><code class="language-sql">CREATE TABLE `users` ( `id` int(11) NOT NULL, `firstname` varchar(100) NOT NULL, `lastname` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `mobilenumber` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `token` varchar(255) NOT NULL, `is_active` enum('0','1') NOT NULL, `date_time` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</code></pre> <h2>Connect Database with PHP 7</h2> <p><span id="ezoic-pub-ad-placeholder-113" class="ezoic-adpicker-ad"></span><span class="ezoic-ad ezoic-at-0 banner-1 banner-1113 adtester-container adtester-container-113" data-ez-name="laravelcode_com-banner-1"><span id="div-gpt-ad-laravelcode_com-banner-1-0" ezaw="336" ezah="280" style="position:relative;z-index:0;display:inline-block;padding:0;width:100%;max-width:1200px;margin-left:auto!important;margin-right:auto!important;min-height:280px;min-width:336px" class="ezoic-ad"><script data-ezscrex="false" data-cfasync="false" type="text/javascript" style="display:none">if(typeof ez_ad_units != 'undefined'){ez_ad_units.push([[336,280],'laravelcode_com-banner-1','ezslot_6',113,'0','0'])};__ez_fad_position('div-gpt-ad-laravelcode_com-banner-1-0');Add the following code in <strong>config/db.php</strong>&nbsp;file.</p> <pre><code class="language-php">&lt;?php // Enable us to use Headers ob_start(); // Set sessions if(!isset($_SESSION)) { session_start(); } $hostname = "localhost"; $username = "phpdemo"; $password = "4Mu99BhzK8dr4vF1"; $dbname = "positronx_db"; $connection = mysqli_connect($hostname, $username, $password, $dbname) or die("Database connection not established.") ?&gt;</code></pre> <p>The&nbsp;<a href="https://www.php.net/manual/en/function.ob-start.php" rel="noopener noreferrer" target="_blank">ob_start()</a>&nbsp;method keeps an eye on output buffering and allow us to use Header.</p> <p><span id="ezoic-pub-ad-placeholder-114" class="ezoic-adpicker-ad"></span><span class="ezoic-ad ezoic-at-0 large-leaderboard-2 large-leaderboard-2114 adtester-container adtester-container-114" data-ez-name="laravelcode_com-large-leaderboard-2"><span id="div-gpt-ad-laravelcode_com-large-leaderboard-2-0" ezaw="300" ezah="250" style="position:relative;z-index:0;display:inline-block;padding:0;min-height:250px;min-width:300px" class="ezoic-ad"><script data-ezscrex="false" data-cfasync="false" type="text/javascript" style="display:none">if(typeof ez_ad_units != 'undefined'){ez_ad_units.push([[300,250],'laravelcode_com-large-leaderboard-2','ezslot_5',114,'0','0'])};__ez_fad_position('div-gpt-ad-laravelcode_com-large-leaderboard-2-0');The <strong>$_SESSION</strong>&nbsp;allow us to save data that we can use in our PHP application, session are alive as long as the browser window is open.</p> <h2>Design User Registration &amp; Login Form UI with Bootstrap 4</h2> <p>To design a user registration &amp; login form UI we are using Bootstrap 4, add the Bootstrap CSS, JavaScript and jQuery link in the head section of the HTML layout.</p> <p>Add the following code in the&nbsp;<strong>signup.php</strong>.</p> <pre><code class="language-html">&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="./css/style.css"&gt; &lt;title&gt;PHP User Registration System Example&lt;/title&gt; &lt;!-- jQuery + Bootstrap JS --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="App"&gt; &lt;div class="vertical-center"&gt; &lt;div class="inner-block"&gt; &lt;form action="" method="post"&gt; &lt;h3&gt;Register&lt;/h3&gt; &lt;div class="form-group"&gt; &lt;label&gt;First name&lt;/label&gt; &lt;input type="text" class="form-control" name="firstname" id="firstName" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Last name&lt;/label&gt; &lt;input type="text" class="form-control" name="lastname" id="lastName" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Email&lt;/label&gt; &lt;input type="email" class="form-control" name="email" id="email" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Mobile&lt;/label&gt; &lt;input type="text" class="form-control" name="mobilenumber" id="mobilenumber" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Password&lt;/label&gt; &lt;input type="password" class="form-control" name="password" id="password" /&gt; &lt;/div&gt; &lt;button type="submit" name="submit" id="submit" class="btn btn-outline-primary btn-lg btn-block"&gt; Sign up &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <p>Add the following code in the&nbsp;<strong>index.php</strong>&nbsp;to create a login form layout.</p> <pre><code class="language-html">&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="css/style.css"&gt; &lt;title&gt;PHP Login System&lt;/title&gt; &lt;!-- jQuery + Bootstrap JS --&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Login form --&gt; &lt;div class="App"&gt; &lt;div class="vertical-center"&gt; &lt;div class="inner-block"&gt; &lt;form action="" method="post"&gt; &lt;h3&gt;Login&lt;/h3&gt; &lt;div class="form-group"&gt; &lt;label&gt;Email&lt;/label&gt; &lt;input type="email" class="form-control" name="email_signin" id="email_signin" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Password&lt;/label&gt; &lt;input type="password" class="form-control" name="password_signin" id="password_signin" /&gt; &lt;/div&gt; &lt;button type="submit" name="login" id="sign_in" class="btn btn-outline-primary btn-lg btn-block"&gt;Sign in&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <p>To add styling in PHP user authentication app go to&nbsp;<strong>css/style.css</strong>&nbsp;and add the following code.</p> <pre><code class="language-css">* { box-sizing: border-box; } body { font-weight: 400; background-color: #EEEFF4; } body, html, .App, .vertical-center { width: 100%; height: 100%; } .navbar { background: #1833FF!important; width: 100%; } .btn-outline-primary { border-color: #1833FF; color: #1833FF; } .btn-outline-primary:hover { background-color: #1833FF; color: #ffffff; } .vertical-center { display: flex; text-align: left; justify-content: center; flex-direction: column; } .inner-block { width: 450px; margin: auto; background: #ffffff; box-shadow: 0px 14px 80px rgba(34, 35, 58, 0.2); padding: 40px 55px 45px 55px; transition: all .3s; border-radius: 20px; } .vertical-center .form-control:focus { border-color: #2554FF; box-shadow: none; } .vertical-center h3 { text-align: center; margin: 0; line-height: 1; padding-bottom: 20px; } label { font-weight: 500; }</code></pre> <h2>Build User Registration System</h2> <p>To create a secure user registration system, we need to get inside the&nbsp;<strong>controllers/register.php</strong>&nbsp;file and place the following code inside of it.</p> <pre><code class="language-php">&lt;?php // Database connection include('config/db.php'); // Swiftmailer lib require_once './lib/vendor/autoload.php'; // Error &amp; success messages global $success_msg, $email_exist, $f_NameErr, $l_NameErr, $_emailErr, $_mobileErr, $_passwordErr; global $fNameEmptyErr, $lNameEmptyErr, $emailEmptyErr, $mobileEmptyErr, $passwordEmptyErr, $email_verify_err, $email_verify_success; // Set empty form vars for validation mapping $_first_name = $_last_name = $_email = $_mobile_number = $_password = ""; if(isset($_POST["submit"])) { $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $email = $_POST["email"]; $mobilenumber = $_POST["mobilenumber"]; $password = $_POST["password"]; // check if email already exist $email_check_query = mysqli_query($connection, "SELECT * FROM users WHERE email = '{$email}' "); $rowCount = mysqli_num_rows($email_check_query); // PHP validation // Verify if form values are not empty if(!empty($firstname) &amp;&amp; !empty($lastname) &amp;&amp; !empty($email) &amp;&amp; !empty($mobilenumber) &amp;&amp; !empty($password)){ // check if user email already exist if($rowCount &gt; 0) { $email_exist = ' &lt;div class="alert alert-danger" role="alert"&gt; User with email already exist! &lt;/div&gt; '; } else { // clean the form data before sending to database $_first_name = mysqli_real_escape_string($connection, $firstname); $_last_name = mysqli_real_escape_string($connection, $lastname); $_email = mysqli_real_escape_string($connection, $email); $_mobile_number = mysqli_real_escape_string($connection, $mobilenumber); $_password = mysqli_real_escape_string($connection, $password); // perform validation if(!preg_match("/^[a-zA-Z ]*$/", $_first_name)) { $f_NameErr = '&lt;div class="alert alert-danger"&gt; Only letters and white space allowed. &lt;/div&gt;'; } if(!preg_match("/^[a-zA-Z ]*$/", $_last_name)) { $l_NameErr = '&lt;div class="alert alert-danger"&gt; Only letters and white space allowed. &lt;/div&gt;'; } if(!filter_var($_email, FILTER_VALIDATE_EMAIL)) { $_emailErr = '&lt;div class="alert alert-danger"&gt; Email format is invalid. &lt;/div&gt;'; } if(!preg_match("/^[0-9]{10}+$/", $_mobile_number)) { $_mobileErr = '&lt;div class="alert alert-danger"&gt; Only 10-digit mobile numbers allowed. &lt;/div&gt;'; } if(!preg_match("/^(?=.*\d)(?=.*[@#\-_$%^&amp;+=§!\?])(?=.*[a-z])(?=.*[A-Z])[<a target="_blank" href="https://laravelcode.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5c5d8ccb4d8af94d88fb5">[email&nbsp;protected]</a>#\-_$%^&amp;+=§!\?]{6,20}$/", $_password)) { $_passwordErr = '&lt;div class="alert alert-danger"&gt; Password should be between 6 to 20 charcters long, contains atleast one special chacter, lowercase, uppercase and a digit. &lt;/div&gt;'; } // Store the data in db, if all the preg_match condition met if((preg_match("/^[a-zA-Z ]*$/", $_first_name)) &amp;&amp; (preg_match("/^[a-zA-Z ]*$/", $_last_name)) &amp;&amp; (filter_var($_email, FILTER_VALIDATE_EMAIL)) &amp;&amp; (preg_match("/^[0-9]{10}+$/", $_mobile_number)) &amp;&amp; (preg_match("/^(?=.*\d)(?=.*[@#\-_$%^&amp;+=§!\?])(?=.*[a-z])(?=.*[A-Z])[<a target="_blank" href="https://laravelcode.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4d4c9dda5c9be85c99ea4">[email&nbsp;protected]</a>#\-_$%^&amp;+=§!\?]{8,20}$/", $_password))){ // Generate random activation token $token = md5(rand().time()); // Password hash $password_hash = password_hash($password, PASSWORD_BCRYPT); // Query $sql = "INSERT INTO users (firstname, lastname, email, mobilenumber, password, token, is_active, date_time) VALUES ('{$firstname}', '{$lastname}', '{$email}', '{$mobilenumber}', '{$password_hash}', '{$token}', '0', now())"; // Create mysql query $sqlQuery = mysqli_query($connection, $sql); if(!$sqlQuery){ die("MySQL query failed!" . mysqli_error($connection)); } // Send verification email if($sqlQuery) { $msg = 'Click on the activation link to verify your email. &lt;br&gt;&lt;br&gt; &lt;a href="http://localhost:8888/php-user-authentication/user_verificaiton.php?token='.$token.'"&gt; Click here to verify email&lt;/a&gt; '; // Create the Transport $transport = (new Swift_SmtpTransport('smtp.gmail.com', 465, 'ssl')) -&gt;setUsername('<a target="_blank" href="https://laravelcode.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb92849e99b48e868a8287ab8c868a8287c5888486">[email&nbsp;protected]</a>') -&gt;setPassword('your_email_password'); // Create the Mailer using your created Transport $mailer = new Swift_Mailer($transport); // Create a message $message = (new Swift_Message('Please Verify Email Address!')) -&gt;setFrom([$email =&gt; $firstname . ' ' . $lastname]) -&gt;setTo($email) -&gt;addPart($msg, "text/html") -&gt;setBody('Hello! User'); // Send the message $result = $mailer-&gt;send($message); if(!$result){ $email_verify_err = '&lt;div class="alert alert-danger"&gt; Verification email coud not be sent! &lt;/div&gt;'; } else { $email_verify_success = '&lt;div class="alert alert-success"&gt; Verification email has been sent! &lt;/div&gt;'; } } } } } else { if(empty($firstname)){ $fNameEmptyErr = '&lt;div class="alert alert-danger"&gt; First name can not be blank. &lt;/div&gt;'; } if(empty($lastname)){ $lNameEmptyErr = '&lt;div class="alert alert-danger"&gt; Last name can not be blank. &lt;/div&gt;'; } if(empty($email)){ $emailEmptyErr = '&lt;div class="alert alert-danger"&gt; Email can not be blank. &lt;/div&gt;'; } if(empty($mobilenumber)){ $mobileEmptyErr = '&lt;div class="alert alert-danger"&gt; Mobile number can not be blank. &lt;/div&gt;'; } if(empty($password)){ $passwordEmptyErr = '&lt;div class="alert alert-danger"&gt; Password can not be blank. &lt;/div&gt;'; } } } ?&gt;</code></pre> <p>Include the database to handle the user data. The&nbsp;<strong>isset()</strong>&nbsp;method is checking the form data when a user clicks on the submit button the same name attribute we passed in the signup form.</p> <p>Extract the user data such as&nbsp;<strong>firstname, lastname, email, mobilenumber</strong>&nbsp;and&nbsp;<strong>password</strong>&nbsp;using the HTTP&nbsp;<strong>$_POST[”]</strong>&nbsp;method.</p> <p><span id="ezoic-pub-ad-placeholder-119" class="ezoic-adpicker-ad"></span><span class="ezoic-ad ezoic-at-0 large-mobile-banner-2 large-mobile-banner-2119 adtester-container adtester-container-119" data-ez-name="laravelcode_com-large-mobile-banner-2"><span id="div-gpt-ad-laravelcode_com-large-mobile-banner-2-0" ezaw="728" ezah="90" style="position:relative;z-index:0;display:inline-block;padding:0;width:100%;max-width:1200px;margin-left:auto!important;margin-right:auto!important;min-height:90px;min-width:728px" class="ezoic-ad"><script data-cfasync="false">