SlideShare a Scribd company logo
User Login in PHP with Session
& MySQL
by Pawan
Table of Contents
● Introduction
● Forging a clean UI with Bootstrap for User Login
● Build and Hook up your MySQL database
● Fun Logic of PHP User Login System
● Conclusion
Introduction
User login functionality in a website is a pretty simple but compulsory
component. In all modern dynamic websites, the client asks for a login and
admin panel so that they can do basic tasks.
Today I will give you a simple and clean-looking login system with PHP and
MySQL. We will maintain the login tracking with PHP Sessions and let
Bootstrap make us a clean UI Design.
Why PHP? Because despite being ancient. As some developers believe.
PHP is fundamental to our web.
Around 81.7% of the websites on the web use PHP as their server-side
language.
And why not PHP?
PHP powers famous CMS(Content Management System) like WordPress and
Joomla. Open Source OOPs frameworks like Laravel and CodeIgniter. And
numerous others.
Reason: PHP is simple and clean to write. Easy-to-understand and
beginner-friendly. Vast community support and adaptability toward developer
needs.
Let’s what will do in this simple project:
● User Login Design with Bootstrap 5
● PHP code for MySQL Database
● Logic to process the login request
● Throw errors if the wrong entry of login credentials
● Redirect to Admin if successful request
● Conclusion
Forging a clean UI with Bootstrap for
User Login
First, we create index.php and write our UI design with the latest Bootstrap 5.
We added Google Fonts Poppins for making our UI look eye-catching.
Whenever possible, we relied on CDN links because it keeps our code
lightweight and less resource intensive.
index.php file
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1">
<!-- CSS -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins&display=swa
p" rel="stylesheet">
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootst
rap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css">
<title>Login</title>
</head>
<body>
<div class="container text-center d-flex align-items-center
min-vh-100">
<div class="card mx-auto bg-info py-5" style="width: 25rem;">
<h1>Login</h1>
<div class="card-body">
<form action="" method="post">
<div class="mb-3">
<label for="email" class="form-label">Email
address</label>
<input type="email" class="form-control" id="email"
name="email" required>
</div>
<div class="mb-3">
<label for="password"
class="form-label">Password</label>
<input type="password" class="form-control"
id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary"
name="login">Login</button>
</form>
</div>
</div>
</div>
<!-- JS -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstra
p.bundle.min.js"></script>
</body>
</html>
Next, we do simple CSS styling in our style.css file. To make our plain
background something fun to look at, I have added a small background image
in webp format. Also, coded in background color as a backup in the case of
legacy browsers that do not support webp format yet.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
background: #f1f1f1;
background: url("../img/email-pattern.webp");
}
Build and Hook up your MySQL
database
Before we start preceding the actual PHP logic part. We need a database for
keeping a record of our login users. And the best choice of course is
MySQL–why because it’s free and open source like PHP. Not to mention very
beginner friendly.
First, go to your PHPMyAdmin whether you’re working online or in the local
environment. And set up your database with a relevant name to your project.
Create Database in PHPMyAdmin in localhost
After the Database is created. Setup a table named users which has mainly
four columns we need: id, email, password, and active. We can also execute
the below SQL code in the PHPMyAdmin SQL tab and this will generate our
table “users”.
CREATE TABLE `users` (
`id` int(5) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`active` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Create a table in the database by running SQL code
Now, we can insert user login details by running the following SQL code. We
are hard coding this now. But we can create a PHP code for the signup
process later. First, we must deploy our user login system.
INSERT INTO `users` (`id`, `email`, `password`, `active`) VALUES
(1, 'test@gmail.com', '1234', 1);
Next in line, we hook up a connection between MySQL and PHP:
connection.php
<?php
$servername = "localhost"; // Enter Your severname here
$username = "root"; // Enter your MySQL database username here
$password = ""; // // Enter your MySQL database password here
$dbname = "ld_call"; // Enter your Database Name here
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Now our UI and database are set. Next, we tackle our User Login process
head-on! Yay! I am excited!
Fun Logic of PHP User Login System
We can all be intimated by logic in programming languages. I myself
remember dreading the C++ practical exams in school. It was so
pain-wrecking process to write the simplest logic. But it is mostly because– we
don’t try to understand why we are writing the code.
Of course, you say to run our program and accomplish something.
But breaking it down into small chunks and bits of pieces is more useful. Let’s
understand with current logic.
We need to determine the login process. But before you write any code. Let’s
write pseudo-code.
What the heck is pseudo-code?
Good question! It’s not actual code. When we write small pieces of notes we
as coders for simplifying the complex logic processes — we call them
pseudo-code.
Sure, our login process is pretty straightforward. And we could code it without
effort.
But if you get in habit of writing pseudo-code before writing a single line of
actual code. You will fall in love with coding. And even page-long logic will
seem like child-play for you.
Pseudo Code for User Login Process:
1. The login form is filed by the user and submit is clicked.
2. Details arrive at the logic part. Where first we clean them for any
unintentional garbage like backslashes, whitespace, etc.
3. Sanitized login details are stored and then compared with values
inside our database for verification.
4. If no match then we pop up an error message for the user.
5. If details match up, we redirect the user to the admin page.
6. Also, code a session that tracks our logged-in user.
7. Set up a logout process that removes our session.
Avoid creating too many pieces when writing pseudo code and vice versa
don’t make too few of them.
Now, let us jump to the actual code:
<?php
require_once("connection.php");
session_start();
function santize($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['login'])) {
$email = santize($_POST['email']);
$password = santize($_POST['password']);
$sql = "SELECT id FROM users WHERE email = '$email' AND password
= '$password' AND active = 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$_SESSION['login_active'] = [$email, $password];
header("Location: admin.php");
exit();
} else {
$_SESSION['errors'] = "Login Error! Check Email & Password";
header("Location: index.php");
exit();
}
}
?>
Before we go to the admin part. Add this snippet block for showing user login
errors. This is to implement a temporary PHP session. Paste this code in a
place where you want to show errors. Mind UI though.
<?php if (isset($_SESSION['errors'])) : ?>
<div class="alert alert-warning alert-dismissible fade
show" role="alert">
<?php
$message = $_SESSION['errors'];
unset($_SESSION['errors']);
echo $message;
?>
<button type="button" class="btn-close"
data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
Insert this snippet code of PHP at top of our index.php and create admin.php
which will be displayed in case of a successful login attempt.
admin.php
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootst
rap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css">
<title>Admin</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="">Admin</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse"
id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
<div class="d-flex">
<a class="btn btn-outline-danger"
href="logout.php">Logout</a>
</div>
</div>
</div>
</nav>
<div class="container">
<h1>Welcome to Admin</h1>
</div>
<!-- Option 1: Bootstrap Bundle with Popper -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstra
p.bundle.min.js"></script>
</body>
</html>
Now we can insert PHP code at top of admin.php which checks whether you
are login session is active. Without this everyone will be able to access your
admin file. So do put this code above your admin.php Html code.
Note: You can use this code on other pages which
need to secure by the login process.
<?php
require_once("connection.php");
session_start();
if (!isset($_SESSION['login_active'])) {
header("Location: index.php");
exit();
}
?>
Now we are pretty much ready to deploy our user login functionality at any
server or localhost.
Conclusion
Now that we have the seen whole process of building a user login system with
PHP, MySQL, and Bootstrap 5. You can just copy the code and deploy it as
needed. Below you download the whole code from my GitHub repository. It
also includes the database file of SQL– so don’t forget to import it if using that
code.
Download Code at Github
And if you are looking for an amazing free code editor. Check out our Why VS
code in the 2022 post.
Lastly if, you think our code helped you solve a need or problem then do
comment and follow us on GitHub and social media. Have fun guys!
Problem Solver is signing off! Ta-da.

More Related Content

Similar to User Login in PHP with Session & MySQL.pdf

PHP on Windows and on Azure
PHP on Windows and on AzurePHP on Windows and on Azure
PHP on Windows and on Azure
Maarten Balliauw
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
Giuliano Iacobelli
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code Igniter
Amzad Hossain
 
Php session
Php sessionPhp session
Php session
argusacademy
 
CyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of UsCyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of Us
Joe Garcia
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
Adam Tomat
 
PSD to WordPress
PSD to WordPressPSD to WordPress
PSD to WordPress
Nile Flores
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
cehwitham
 
Php My Sql Security 2007
Php My Sql Security 2007Php My Sql Security 2007
Php My Sql Security 2007
Aung Khant
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
Rich Helton
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
Joao Lucas Santana
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
php
phpphp
How not to suck at Cyber Security
How not to suck at Cyber SecurityHow not to suck at Cyber Security
How not to suck at Cyber Security
Chris Watts
 
PHP on Windows
PHP on WindowsPHP on Windows
PHP on Windows
Maarten Balliauw
 
PHP on Windows
PHP on WindowsPHP on Windows
PHP on Windows
guest60c7659
 
Submit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdfSubmit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdf
Be Problem Solver
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolment
Rajib Ahmed
 
Extending Oracle SSO
Extending Oracle SSOExtending Oracle SSO
Extending Oracle SSO
kurtvm
 

Similar to User Login in PHP with Session & MySQL.pdf (20)

PHP on Windows and on Azure
PHP on Windows and on AzurePHP on Windows and on Azure
PHP on Windows and on Azure
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code Igniter
 
Php session
Php sessionPhp session
Php session
 
CyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of UsCyberArk Impact 2017 - REST for the Rest of Us
CyberArk Impact 2017 - REST for the Rest of Us
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
PSD to WordPress
PSD to WordPressPSD to WordPress
PSD to WordPress
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
 
Php My Sql Security 2007
Php My Sql Security 2007Php My Sql Security 2007
Php My Sql Security 2007
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)Desenvolvimento web com Ruby on Rails (parte 6)
Desenvolvimento web com Ruby on Rails (parte 6)
 
Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
 
php
phpphp
php
 
How not to suck at Cyber Security
How not to suck at Cyber SecurityHow not to suck at Cyber Security
How not to suck at Cyber Security
 
PHP on Windows
PHP on WindowsPHP on Windows
PHP on Windows
 
PHP on Windows
PHP on WindowsPHP on Windows
PHP on Windows
 
Submit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdfSubmit form with Ajax and jQuery without reloading page.pdf
Submit form with Ajax and jQuery without reloading page.pdf
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolment
 
Extending Oracle SSO
Extending Oracle SSOExtending Oracle SSO
Extending Oracle SSO
 

Recently uploaded

9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Neo4j
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 

Recently uploaded (20)

9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid ResearchHarnessing the Power of NLP and Knowledge Graphs for Opioid Research
Harnessing the Power of NLP and Knowledge Graphs for Opioid Research
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 

User Login in PHP with Session & MySQL.pdf

  • 1. User Login in PHP with Session & MySQL by Pawan Table of Contents ● Introduction ● Forging a clean UI with Bootstrap for User Login ● Build and Hook up your MySQL database ● Fun Logic of PHP User Login System ● Conclusion Introduction User login functionality in a website is a pretty simple but compulsory component. In all modern dynamic websites, the client asks for a login and admin panel so that they can do basic tasks.
  • 2. Today I will give you a simple and clean-looking login system with PHP and MySQL. We will maintain the login tracking with PHP Sessions and let Bootstrap make us a clean UI Design. Why PHP? Because despite being ancient. As some developers believe. PHP is fundamental to our web. Around 81.7% of the websites on the web use PHP as their server-side language. And why not PHP? PHP powers famous CMS(Content Management System) like WordPress and Joomla. Open Source OOPs frameworks like Laravel and CodeIgniter. And numerous others. Reason: PHP is simple and clean to write. Easy-to-understand and beginner-friendly. Vast community support and adaptability toward developer needs. Let’s what will do in this simple project: ● User Login Design with Bootstrap 5 ● PHP code for MySQL Database ● Logic to process the login request ● Throw errors if the wrong entry of login credentials ● Redirect to Admin if successful request ● Conclusion Forging a clean UI with Bootstrap for User Login
  • 3. First, we create index.php and write our UI design with the latest Bootstrap 5. We added Google Fonts Poppins for making our UI look eye-catching. Whenever possible, we relied on CDN links because it keeps our code lightweight and less resource intensive. index.php file <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSS --> <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swa p" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootst rap.min.css" rel="stylesheet"> <link rel="stylesheet" href="assets/css/style.css"> <title>Login</title>
  • 4. </head> <body> <div class="container text-center d-flex align-items-center min-vh-100"> <div class="card mx-auto bg-info py-5" style="width: 25rem;"> <h1>Login</h1> <div class="card-body"> <form action="" method="post"> <div class="mb-3"> <label for="email" class="form-label">Email address</label> <input type="email" class="form-control" id="email" name="email" required> </div> <div class="mb-3"> <label for="password" class="form-label">Password</label> <input type="password" class="form-control" id="password" name="password" required>
  • 5. </div> <button type="submit" class="btn btn-primary" name="login">Login</button> </form> </div> </div> </div> <!-- JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstra p.bundle.min.js"></script> </body> </html> Next, we do simple CSS styling in our style.css file. To make our plain background something fun to look at, I have added a small background image in webp format. Also, coded in background color as a backup in the case of legacy browsers that do not support webp format yet. * { margin: 0; padding: 0;
  • 6. box-sizing: border-box; } body { font-family: 'Poppins', sans-serif; background: #f1f1f1; background: url("../img/email-pattern.webp"); } Build and Hook up your MySQL database Before we start preceding the actual PHP logic part. We need a database for keeping a record of our login users. And the best choice of course is MySQL–why because it’s free and open source like PHP. Not to mention very beginner friendly. First, go to your PHPMyAdmin whether you’re working online or in the local environment. And set up your database with a relevant name to your project.
  • 7. Create Database in PHPMyAdmin in localhost After the Database is created. Setup a table named users which has mainly four columns we need: id, email, password, and active. We can also execute the below SQL code in the PHPMyAdmin SQL tab and this will generate our table “users”. CREATE TABLE `users` ( `id` int(5) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `active` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 8. Create a table in the database by running SQL code Now, we can insert user login details by running the following SQL code. We are hard coding this now. But we can create a PHP code for the signup process later. First, we must deploy our user login system. INSERT INTO `users` (`id`, `email`, `password`, `active`) VALUES (1, 'test@gmail.com', '1234', 1); Next in line, we hook up a connection between MySQL and PHP: connection.php <?php $servername = "localhost"; // Enter Your severname here $username = "root"; // Enter your MySQL database username here $password = ""; // // Enter your MySQL database password here $dbname = "ld_call"; // Enter your Database Name here
  • 9. $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } Now our UI and database are set. Next, we tackle our User Login process head-on! Yay! I am excited! Fun Logic of PHP User Login System We can all be intimated by logic in programming languages. I myself remember dreading the C++ practical exams in school. It was so pain-wrecking process to write the simplest logic. But it is mostly because– we don’t try to understand why we are writing the code. Of course, you say to run our program and accomplish something. But breaking it down into small chunks and bits of pieces is more useful. Let’s understand with current logic. We need to determine the login process. But before you write any code. Let’s write pseudo-code. What the heck is pseudo-code? Good question! It’s not actual code. When we write small pieces of notes we as coders for simplifying the complex logic processes — we call them pseudo-code.
  • 10. Sure, our login process is pretty straightforward. And we could code it without effort. But if you get in habit of writing pseudo-code before writing a single line of actual code. You will fall in love with coding. And even page-long logic will seem like child-play for you. Pseudo Code for User Login Process: 1. The login form is filed by the user and submit is clicked. 2. Details arrive at the logic part. Where first we clean them for any unintentional garbage like backslashes, whitespace, etc. 3. Sanitized login details are stored and then compared with values inside our database for verification. 4. If no match then we pop up an error message for the user. 5. If details match up, we redirect the user to the admin page. 6. Also, code a session that tracks our logged-in user. 7. Set up a logout process that removes our session. Avoid creating too many pieces when writing pseudo code and vice versa don’t make too few of them. Now, let us jump to the actual code: <?php require_once("connection.php"); session_start(); function santize($data) { $data = trim($data);
  • 11. $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } if (isset($_POST['login'])) { $email = santize($_POST['email']); $password = santize($_POST['password']); $sql = "SELECT id FROM users WHERE email = '$email' AND password = '$password' AND active = 1"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $_SESSION['login_active'] = [$email, $password]; header("Location: admin.php"); exit(); } else { $_SESSION['errors'] = "Login Error! Check Email & Password"; header("Location: index.php");
  • 12. exit(); } } ?> Before we go to the admin part. Add this snippet block for showing user login errors. This is to implement a temporary PHP session. Paste this code in a place where you want to show errors. Mind UI though. <?php if (isset($_SESSION['errors'])) : ?> <div class="alert alert-warning alert-dismissible fade show" role="alert"> <?php $message = $_SESSION['errors']; unset($_SESSION['errors']); echo $message; ?> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> <?php endif; ?>
  • 13. Insert this snippet code of PHP at top of our index.php and create admin.php which will be displayed in case of a successful login attempt. admin.php <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootst rap.min.css" rel="stylesheet"> <link rel="stylesheet" href="assets/css/style.css"> <title>Admin</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  • 14. <div class="container-fluid"> <a class="navbar-brand" href="">Admin</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul> <div class="d-flex"> <a class="btn btn-outline-danger" href="logout.php">Logout</a> </div> </div> </div> </nav> <div class="container">
  • 15. <h1>Welcome to Admin</h1> </div> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstra p.bundle.min.js"></script> </body> </html> Now we can insert PHP code at top of admin.php which checks whether you are login session is active. Without this everyone will be able to access your admin file. So do put this code above your admin.php Html code. Note: You can use this code on other pages which need to secure by the login process. <?php require_once("connection.php"); session_start(); if (!isset($_SESSION['login_active'])) { header("Location: index.php"); exit();
  • 16. } ?> Now we are pretty much ready to deploy our user login functionality at any server or localhost. Conclusion Now that we have the seen whole process of building a user login system with PHP, MySQL, and Bootstrap 5. You can just copy the code and deploy it as needed. Below you download the whole code from my GitHub repository. It also includes the database file of SQL– so don’t forget to import it if using that code. Download Code at Github And if you are looking for an amazing free code editor. Check out our Why VS code in the 2022 post. Lastly if, you think our code helped you solve a need or problem then do comment and follow us on GitHub and social media. Have fun guys! Problem Solver is signing off! Ta-da.