Search Phppot Demo About Contact Me
PHP PHP Login Form with MySQL database Hi, I'm Vincy. I help build
Learn PHP
PHP Introduction
and form validation websites, grow businesses, big
and small. If that is what you
PHP Basics want, contact me.
by Vincy. Last modified on July 19th, 2022.
PHP Shopping Cart
I'm currently available for freelance work.
Payment Gateway
Login form – an entry point of a website to authenticate users. PHP login
Contact Form [email protected]
system requires users to register with the application first to log in later.
PHP Login Registration
User Registration in PHP with The registered users are managed in a database at the back end. On each login
Login: Form with MySQL and attempt via the PHP login form, it verifies the database to find a match.
Code Download Get Connected
PHP Login Script with Session It is a very simple and essential job. At the same time, it should be designed
PHP Login Form with MySQL with security to guard the site. It should filter anonymous hits 100% not to let
database and form validation unregistered users get in.
PHP Login with OTP
Authentication The PHP login form action stores the logged-in user in a session. It uses PHP
AJAX Based Login $_SESSION one of its superglobals. It’s better to validate the existence of this
Registration System with session at the beginning of each page to be protected. Popular Tutorials
jQuery Lightbox
Secure Remember Me for This PHP code can also be used to add an admin login for your control panel. Simple PHP Shopping Cart
Login using PHP Session and Also, it can be used as a common authentication entry for both admin and user Stripe Payment Gateway Integration using
Cookies
side of an application. PHP
PHP Wizard Like Registration
User Registration in PHP with Login: Form
PHP User Authentication with with MySQL and Code Download
MySQL PHP login form code
PHP Contact Form
User Activation Email Sending
Script in PHP This example is to design a PHP login form working with backend processing. How to Create Dynamic Stacked Bar,
The login page in PHP shows the UI elements like social login, forgot password Doughnut and Pie charts in PHP with Chart.js
Facebook Open Authentication
in PHP and etc.
Bootstrap Login Form Page
Template Example It posts data to process a username/password-based login authentication.
Material Design Login Form This example uses the database to authenticate the user login. Testimonials
with PHP and jQuery
PHP Forgot Password Recover This PHP login system is capable of linking the following code to the additional “The process was fast and very professional.
Code login form controls. The whole time we could follow the work and
PHP Password Validation correct small details. As we got new ideas
Check for Strength 1. Link PHP forgot/reset password feature. under the process Vincy was able to
How to Implement OTP SMS 2. Link User registration PHP example to the sign-up option. implement them without delay ...”
Mobile Verification in PHP
3. Also, Link Oauth login with Facebook, Twitter and Linkedin. Steen Hertzum Kirchhoff, JobRater, Sweeden
with TextLocal
Show PHP Captcha on Failed
Login Attempts View More Testimonials
Double Opt-In Subscription
Form with Secure Hash using
PHP
Comments System
Types, Variables & Operators
PHP Strings
PHP Arrays
PHP Functions
PHP OOPS
Event Management System
PHP Mail
PHP Forms
Advanced
PHP AJAX
RESTful API
PHP Databases
PHP Sessions and Cookies
Error and Exception Handling
File Upload
File Import Export
Files and Directories
PHP Date Time
PHP XML
PHP CSV
PHP JSON HTML form template
PHP Code Samples
Library The landing page renders this template into the UI to let the user log in. It will
PHP Freelancer happen when there is no logged-in session.
jQuery
This form accepts the user’s login details username or email and a secure
JavaScript password. The submit event triggers the PHP login form validation and posts
the login data to the PHP.
WordPress
MySQL This PHP login form is responsive to the different viewport sizes. It uses
simple CSS media queries for adding site responsiveness.
CSS
The form tag calls a JavaScript function validate() on the submit event. The
below code includes the PHP login form validation script at the end.
Share this page
Share
view/login-form.php
<form action="login-action.php" method="post" id="frmLog
onSubmit="return validate();">
Tweet <div class="login-form-container">
<div class="form-head">Login</div>
Share <?php
if (isset($_SESSION["errorMessage"])) {
?>
<div class="error-message"><?php echo $_SESSION
<?php
unset($_SESSION["errorMessage"]);
}
?>
<div class="field-column">
<div>
<label for="username">Username</label><s
class="error-info"></span>
</div>
<div>
<input name="user_name" id="user_name" t
class="demo-input-box" placeholder="
</div>
</div>
<div class="field-column">
<div>
<label for="password">Password</label><s
class="error-info"></span>
</div>
<div>
<input name="password" id="password" typ
class="demo-input-box" placeholder="
</div>
</div>
<div class=field column>
PHP login form action
A PHP endpoint script that is an action target of the login form handles the
login data.
This login page in PHP sanitizes the data before processing them. It uses
PHP filter_var function to sanitize the user entered authentication details.
It conducts the authentication process after receiving the user credentials.
This program puts the authenticated user details in a session. Then, it
acknowledges the user accordingly.
login-action.php
<?php
namespace Phppot;
use \Phppot\Member;
if (! empty($_POST["login"])) {
session_start();
$username = filter_var($_POST["user_name"], FILTER_SANITIZE_ST
$password = filter_var($_POST["password"], FILTER_SANITIZE_STR
require_once (__DIR__ . "/class/Member.php");
$member = new Member();
$isLoggedIn = $member->processLogin($username, $password);
if (! $isLoggedIn) {
$_SESSION["errorMessage"] = "Invalid Credentials";
}
header("Location: ./index.php");
exit();
}
PHP login authentication model class
It contains the processLogin() function to check the PHP login form data with
the database. It uses PHP password_verify() function to validate the user-
entered password. This PHP function compares the password with the hashed
password on the database.
The getMemberById() function reads the member result by member id. After
successful login, it is called from the case to display the dashboard. It returns
the array of data to be displayed on the dashboard.
class/Member.php
<?php
namespace Phppot;
use \Phppot\DataSource;
class Member
{
private $dbConn;
private $ds;
function __construct()
{
require_once "DataSource.php";
$this->ds = new DataSource();
}
function getMemberById($memberId)
{
$query = "select * FROM registered_users WHERE id = ?";
$paramType = "i";
$paramArray = array($memberId);
$memberResult = $this->ds->select($query, $paramType, $p
return $memberResult;
}
public function processLogin($username, $password) {
$query = "select * FROM registered_users WHERE user_name
$paramType = "ss";
$paramArray = array($username, $username);
$memberResult = $this->ds->select($query, $paramType, $p
Show dashboard and logout link after PHP login
After successful login, the site says there exists a session of the logged-in
user. It can be shown in different ways.
In most sites, the site header displays the logged-in user’s profile link. It can be
a clickable avatar that slides down a profile menu.
This PHP login system redirects the user to a dashboard page after login. This
dashboard page shows a welcome message, about-user with an avatar.
The landing page checks the PHP session if any user has already login. If so, it
will redirect to this dashboard page.
view/dashboard.php
<?php
namespace Phppot;
use \Phppot\Member;
if (! empty($_SESSION["userId"])) {
require_once __DIR__ . './../class/Member.php';
$member = new Member();
$memberResult = $member->getMemberById($_SESSION["userId"]);
if(!empty($memberResult[0]["display_name"])) {
$displayName = ucwords($memberResult[0]["display_name"])
} else {
$displayName = $memberResult[0]["user_name"];
}
}
?>
<html>
<head>
<title>User Login</title>
<style>
body {
font-family: Arial;
color: #333;
font-size: 0.95em;
}
.dashboard {
background: #d2edd5;
margin: 15px auto;
line-height: 1.8em;
color: #333;
border-radius: 4px;
padding: 30px;
Logging out from the site
This is a general routine to log out from the site. The following script clears the
PHP session. Then it redirects back to login page in PHP.
Sometimes, the logout case may clear cookies. Example: In the case of using a
cookie-based Remember Me feature in login.
view/dashboard.php
<?php
session_start();
$_SESSION["user_id"] = "";
session_destroy();
header("Location: index.php");
Files structure
See the below image that shows the file structure of this simple PHP login
form example. It contains a featured login form UI with the application view
files.
The login action calls the PHP model on the submit event. It performs backend
authentication with the database.
Database script
Look at this SQL script which contains the CREATE statement and sample row
data.
By importing this SQL, it creates database requisites in your development
environment.
The sample data helps to try a login that returns success response on the
authentication.
Test data: username: kate_91 password: admin123
sql/database.sql
--
-- Database: `blog_eg`
--
-- --------------------------------------------------------
--
-- Table structure for table `registered_users`
--
CREATE TABLE `registered_users` (
`id` int(8) NOT NULL,
`user_name` varchar(255) NOT NULL,
`display_name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`photo` text DEFAULT NULL,
`about` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `registered_users`
--
INSERT INTO `registered_users` (`id`, `user_name`, `display_name
(1, 'kate_91', 'Kate Winslet', '$2y$10$LVISX0lCiIsQU1vUX/dAGunHT
--
-- Indexes for dumped tables
--
--
-- Indexes for table `registered users`
Secure DataSource using MySQL with prepared
statements
This DataSource is a common file to be used in any stand-alone PHP
application. It uses MySQLi with prepared statement to execute database
queries. It works with PHP 8 and 7+
class/DataSource.php
This class is available in the project download zip file below. It is a common
wrapper for MySQL using PreparedStatement.
Conclusion
We have seen a simple example on the PHP login form. Hope this will be useful
to have a featured, responsive login form.
The article interlinks the constellations of a login form. It will be helpful to
integrate more features with the existing login template.
Let me know your feedback on the comments section if you need any
improvements on this PHP login system.
download
Written by Vincy, a web developer with 15+ years of
experience and a Masters degree in Computer Science. She
specializes in building modern, lightweight websites using
PHP, JavaScript, React, and related technologies. Phppot
helps you in mastering web development through over a
decade of publishing quality tutorials.
Comments to “PHP Login Form with MySQL
database and form validation”
bob
August 1, 2022 at 2:30 am
Thanks a lot
All your script are awesome, simple and beautifull! ;)
Thanks
Reply
Vincy
August 2, 2022 at 7:59 pm
Welcome Bob.
Reply
Erick Enrique Hernandez Aguillon
August 4, 2022 at 10:24 pm
It would be great if you create a tutorial on how to login and register with
Google and Facebook on a website
Reply
Vincy
August 5, 2022 at 7:59 pm
Hi Erick,
I have already written tutorials on them. Please use the search bar
in the header and you will land in it easily. Thanks.
Reply
Leave a Reply
Comment
Name *
Email *
Post Comment
Related Tutorials
★ User Registration in PHP with Login: Form with MySQL and Code
Download
★ PHP Login Script with Session
★ Secure Remember Me for Login using PHP Session and Cookies
↑ Back to Top
Looking for an expert PHP freelance web developer?
Do you want to build a modern, lightweight, responsive website quickly? Contact Me
Free Weekly Newsletter
Contact | LinkedIn | Facebook | © 2013 - 2025 Phppot
Enter your email here Subscribe
Privacy Policy Terms of Use Cancellation & Refund Policy
Privacy guaranteed, no spam ever.