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="//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="//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="//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="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//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="//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="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//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="//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="//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="//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="//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">if[typeof ez_ad_units != 'undefined']{ez_ad_units.push[[[728,90],'laravelcode_com-large-mobile-banner-2','ezslot_13',119,'0','0']]};__ez_fad_position['div-gpt-ad-laravelcode_com-large-mobile-banner-2-0'];Validate if the email provided by the user already exists in the database using the SQL script via <strong>mysqli_query[]</strong>&nbsp;method.</p> <p>Check if the form values are not empty.</p> <p>Verify if user email already exists, then display the error using the Bootstrap alert message component. We make the error message a global variable so that we can show it to the user.</p> <p>The&nbsp;<strong>mysqli_real_escape_string[]</strong>&nbsp;method cleans the data before sending to the database.</p> <p>The&nbsp;<strong>preg_match[]</strong>&nbsp;method does the PHP validation for the name, mobile name and password. For validating email value, we used the&nbsp;<strong>filter_var[]</strong>&nbsp;method. We wrapped the errors and set it to global as well.</p> <p>We need to generate the random token using the&nbsp;<strong>md5[rand[].time[]]</strong>&nbsp;method to send verification email to the user email id.</p> <p>To securely hash the password, we used the&nbsp;<a href="//www.php.net/manual/en/function.password-hash.php" rel="noopener noreferrer" target="_blank">password_hash[]</a>&nbsp;method. The password_hash[] creates a new password hash using a secure one-way hashing algorithm.</p> <p>We need to install the SwiftMailer php plugin to send the verification mail to the user, i used the following composer command to install the SwiftMailer library. Make sure you have composer installed on your development machine.</p> <pre><code class="language-php">composer require "swiftmailer/swiftmailer:^6.0"</code></pre> <p>We need to import the&nbsp;<a href="//swiftmailer.symfony.com/" rel="noopener noreferrer" target="_blank">SwiftMailer</a>&nbsp;library and add the SwiftMailer script also define the email template that will be sent to the user.</p> <p>Now, we need to implement the user authentication logic inside the&nbsp;<strong>signup.php</strong>&nbsp;file.</p> <pre><code class="language-html">&lt;?php include['./controllers/register.php']; ?&gt; &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="//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="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include['./header.php']; ?&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;?php echo $success_msg; ?&gt; &lt;?php echo $email_exist; ?&gt; &lt;?php echo $email_verify_err; ?&gt; &lt;?php echo $email_verify_success; ?&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;?php echo $fNameEmptyErr; ?&gt; &lt;?php echo $f_NameErr; ?&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;?php echo $l_NameErr; ?&gt; &lt;?php echo $lNameEmptyErr; ?&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;?php echo $_emailErr; ?&gt; &lt;?php echo $emailEmptyErr; ?&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;?php echo $_mobileErr; ?&gt; &lt;?php echo $mobileEmptyErr; ?&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;?php echo $_passwordErr; ?&gt; &lt;?php echo $passwordEmptyErr; ?&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> <h2>User Email Verification Script in PHP 7</h2> <p>We have defined the SwiftMailer configurations in the&nbsp;<strong>register.php</strong>&nbsp;file, now implement the user verification script to send verification email.</p> <p>Add the following code in&nbsp;<strong>controllers/user_activation.php</strong>&nbsp;file.</p> <pre><code class="language-php">&lt;?php // Database connection include['./config/db.php']; global $email_verified, $email_already_verified, $activation_error; // GET the token = ?token if[!empty[$_GET['token']]]{ $token = $_GET['token']; } else { $token = ""; } if[$token != ""] { $sqlQuery = mysqli_query[$connection, "SELECT * FROM users WHERE token = '$token' "]; $countRow = mysqli_num_rows[$sqlQuery]; if[$countRow == 1]{ while[$rowData = mysqli_fetch_array[$sqlQuery]]{ $is_active = $rowData['is_active']; if[$is_active == 0] { $update = mysqli_query[$connection, "UPDATE users SET is_active = '1' WHERE token = '$token' "]; if[$update]{ $email_verified = '&lt;div class="alert alert-success"&gt; User email successfully verified! &lt;/div&gt; '; } } else { $email_already_verified = '&lt;div class="alert alert-danger"&gt; User email already verified! &lt;/div&gt; '; } } } else { $activation_error = '&lt;div class="alert alert-danger"&gt; Activation error! &lt;/div&gt; '; } } ?&gt;</code></pre> <p>Add the following code in&nbsp;<strong>user_verification.php</strong>&nbsp;file.</p> <pre><code class="language-html">&lt;?php include['./controllers/user_activation.php']; ?&gt; &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="//stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="./css/style.css"&gt; &lt;title&gt;User Verification&lt;/title&gt; &lt;!-- jQuery + Bootstrap JS --&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="jumbotron text-center"&gt; &lt;h2 class="display-4"&gt;User Email Verification Demo&lt;/h2&gt; &lt;div class="col-12 mb-5 text-center"&gt; &lt;?php echo $email_already_verified; ?&gt; &lt;?php echo $email_verified; ?&gt; &lt;?php echo $activation_error; ?&gt; &lt;/div&gt; &lt;p class="lead"&gt;If user account is verified then click on the following button to login.&lt;/p&gt; &lt;a class="btn btn-lg btn-success" href="//localhost:8888/php-user-authentication/index.php" &gt;Click to Login &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <h2>Build PHP 7 Login System with MySQL</h2> <p>The following code allows access to only those users who have verified their email address. A non-verified user can not access in the app, and We are also storing the logged-in user’s data into the PHP Session and with the help of&nbsp;<strong>header[“Location: page_url.php”]</strong>&nbsp;method redirecting the logged-in user to dashboard.php page.</p> <p>To create PHP 7 Login system with MySQL, Add the following code in&nbsp;<strong>controllers/login.php</strong>&nbsp;file.</p> <pre><code class="language-php">&lt;?php // Database connection include['config/db.php']; global $wrongPwdErr, $accountNotExistErr, $emailPwdErr, $verificationRequiredErr, $email_empty_err, $pass_empty_err; if[isset[$_POST['login']]] { $email_signin = $_POST['email_signin']; $password_signin = $_POST['password_signin']; // clean data $user_email = filter_var[$email_signin, FILTER_SANITIZE_EMAIL]; $pswd = mysqli_real_escape_string[$connection, $password_signin]; // Query if email exists in db $sql = "SELECT * From users WHERE email = '{$email_signin}' "; $query = mysqli_query[$connection, $sql]; $rowCount = mysqli_num_rows[$query]; // If query fails, show the reason if[!$query]{ die["SQL query failed: " . mysqli_error[$connection]]; } if[!empty[$email_signin] &amp;&amp; !empty[$password_signin]]{ if[!preg_match["/^[?=.*\d][?=.*[@#\-_$%^&amp;+=§!\?]][?=.*[a-z]][?=.*[A-Z]][<a target="_blank" href="//laravelcode.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="61514c58204c3b004c1b21">[email&nbsp;protected]</a>#\-_$%^&amp;+=§!\?]{6,20}$/", $pswd]] { $wrongPwdErr = '&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;'; } // Check if email exist if[$rowCount &lt;= 0] { $accountNotExistErr = '&lt;div class="alert alert-danger"&gt; User account does not exist. &lt;/div&gt;'; } else { // Fetch user data and store in php session while[$row = mysqli_fetch_array[$query]] { $id = $row['id']; $firstname = $row['firstname']; $lastname = $row['lastname']; $email = $row['email']; $mobilenumber = $row['mobilenumber']; $pass_word = $row['password']; $token = $row['token']; $is_active = $row['is_active']; } // Verify password $password = password_verify[$password_signin, $pass_word]; // Allow only verified user if[$is_active == '1'] { if[$email_signin == $email &amp;&amp; $password_signin == $password] { header["Location: ./dashboard.php"]; $_SESSION['id'] = $id; $_SESSION['firstname'] = $firstname; $_SESSION['lastname'] = $lastname; $_SESSION['email'] = $email; $_SESSION['mobilenumber'] = $mobilenumber; $_SESSION['token'] = $token; } else { $emailPwdErr = '&lt;div class="alert alert-danger"&gt; Either email or password is incorrect. &lt;/div&gt;'; } } else { $verificationRequiredErr = '&lt;div class="alert alert-danger"&gt; Account verification is required for login. &lt;/div&gt;'; } } } else { if[empty[$email_signin]]{ $email_empty_err = "&lt;div class='alert alert-danger email_alert'&gt; Email not provided. &lt;/div&gt;"; } if[empty[$password_signin]]{ $pass_empty_err = "&lt;div class='alert alert-danger email_alert'&gt; Password not provided. &lt;/div&gt;"; } } } ?&gt;</code></pre> <p>To implement the sign-in logic in the login page, Add the following code in&nbsp;<strong>controllers/index.php</strong>&nbsp;file.</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="//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 &amp; Login System Demo&lt;/title&gt; &lt;!-- jQuery + Bootstrap JS --&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Header --&gt; &lt;?php include['../php-user-authentication/header.php']; ?&gt; &lt;!-- Login script --&gt; &lt;?php include['./controllers/login.php']; ?&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;?php echo $accountNotExistErr; ?&gt; &lt;?php echo $emailPwdErr; ?&gt; &lt;?php echo $verificationRequiredErr; ?&gt; &lt;?php echo $email_empty_err; ?&gt; &lt;?php echo $pass_empty_err; ?&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> <h2>Display Logged-in User’s Data &amp; Log Out Script</h2> <p>Add the following code in&nbsp;<strong>dashboard.php</strong>&nbsp;to display the user data to the logged-in users only.</p> <pre><code class="language-html">&lt;?php include['config/db.php']; ?&gt; &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="//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="//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="//stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container mt-5"&gt; &lt;div class="d-flex justify-content-center"&gt; &lt;div class="card" style="width: 25rem"&gt; &lt;div class="card-body"&gt; &lt;h5 class="card-title text-center mb-4"&gt;User Profile&lt;/h5&gt; &lt;h6 class="card-subtitle mb-2 text-muted"&gt;&lt;?php echo $_SESSION['firstname']; ?&gt; &lt;?php echo $_SESSION['lastname']; ?&gt;&lt;/h6&gt; &lt;p class="card-text"&gt;Email address: &lt;?php echo $_SESSION['email']; ?&gt;&lt;/p&gt; &lt;p class="card-text"&gt;Mobile number: &lt;?php echo $_SESSION['mobilenumber']; ?&gt;&lt;/p&gt; &lt;a class="btn btn-danger btn-block" href="logout.php"&gt;Log out&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <p>Now, we need to destroy the session to Sign-out the user from the user auth system. We have already passed the logout.php link to the logout button in dashboard file.</p> <p>Open&nbsp;<strong>logout.php</strong>&nbsp;and place the following code in it.</p> <pre><code class="language-php">&lt;?php session_start[]; session_destroy[]; header["Location: //localhost:8888/php-user-authentication/index.php"] ;?&gt;</code></pre> <h2>Conclusion</h2> <p>So, this was the PHP 7 User authentication &amp; Login App. I hope you have got the basic idea of how can we make a login and auth sytem with PHP and MySQL. We covered some of the essential topics such as sending a verification email to user, securely hash the password.</p> <span id="ezoic-pub-ad-placeholder-109"></span><span class="ezoic-ad ezoic-at-0 large-mobile-banner-1 large-mobile-banner-1109 adtester-container adtester-container-109" data-ez-name="laravelcode_com-large-mobile-banner-1"><span id="div-gpt-ad-laravelcode_com-large-mobile-banner-1-0" ezaw="580" ezah="400" 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:400px;min-width:580px" class="ezoic-ad"><script data-cfasync="false">if[typeof ez_ad_units != 'undefined']{ez_ad_units.push[[[580,400],'laravelcode_com-large-mobile-banner-1','ezslot_4',109,'0','0']]};__ez_fad_position['div-gpt-ad-laravelcode_com-large-mobile-banner-1-0'];

Author : Harsukh Makwana

Bài mới nhất

Chủ Đề