Secure login system with PHP and MySQL (2023)

In this tutorial I will show you how to create your own secure PHP login system. A login form is what your website visitors can use to log into your website to access restricted content such as a profile page. We will use MySQL to retrieve account information from the database.

Öextended packageincludes additional resources and a link to download the source code.


  1. beginning
    1. requirements
    2. What you will learn in this tutorial
  2. Creating the login form layout
  3. Database creation and table configuration
  4. User authentication with PHP
  5. Creation of homepages
  6. profile page creation
  7. Creating the logout script

1. Getting Started

There are a few steps we need to go through before creating our secure login system. We need to set up our web server environment and make sure the required extensions are enabled.

1.1. requirements

  • If you don't have a local web server set up, I recommend downloading and installing itXAMPPGenericName.
  • XAMPP is a cross-platform web server package that contains the essentials for backend developers. Includes PHP, MySQL, Apache, phpMyAdmin and more. With XAMPP, there is no need to install all the software separately.

1.2. What you will learn in this tutorial

  • shape design— Create a registration form using HTML5 and CSS3.
  • Prepared SQL queries— How to properly prepare SQL queries to avoid SQL injection and thus prevent your database from being exposed.
  • basic validation— Validation of form data sent to the server via GET and POST requests (username, password, email, etc.).
  • session management— Initialize sessions and save retrieved database results. Sessions are stored on the server and associated with a unique ID that is stored in the browser.

1.3. Configuration and file structure

Now we can start our web server and create the files and directories that we will use for our login system.

  • OpenXAMPPName Control Panel
  • Click next to the Apache moduleBegin
  • Click next to the MySQL moduleBegin
  • Navigate to the XAMPP installation directory (C:\xampp)
  • open thishtdocsdirectory
  • Create the following directories and files:

file structure

\-- phplogin
|-- style.css
|-- exit.php
|-- start.php
|-- profile.php

Each file consists of the following:

  • index.html— The registration form created with HTML5 and CSS3. We don't need to use PHP in this file. So we can save it as plain HTML.
  • style.css— The style sheet (CSS3) for our secure login system.
  • authenticate.php— Authenticate users, connect to database, validate form data, retrieve results from database and create new sessions.
  • exit.php— Destroy initiated sessions and redirect user to login page.
  • home.php— Simple homepage for registered users.
  • profile.php— Get user account details from our MySQL database and populate it with PHP and HTML.

2. Creating the login form layout

We will now create a form that our users can use to enter their data and submit it for processing. We will use HTML and CSS for this part of the tutorial as PHP is not required on this page.

edit theindex.htmlFile with your favorite code editor and add the following code:


<!DOCTYPE html><html><head><meta charset="utf-8"><title>Anmelden</title><link rel="stylesheet" href=" /v5.7.1/css/all.css"></head><body><div class="login"><h1>Anmeldung</h1><form action="authenticate.php" method= "post"> <label for="username"><i class="fas fa-user"></i></label><input type="text" name="username" placeholder="Username" id="username" obrigatório ><label for="password"><i class="fas fa-lock"></i></label><input type="password" name="password" placeholder ="Password" id="password" obrigatorio <input type="submit" value="Login"></form></div></body></html>

When we navigate to the index page in our web browser, it looks like this:


Secure login system with PHP and MySQL (1)

Pretty easy, right? Let's edit oursstyle.cssArchive and implement code that improves the appearance of the form.

Add the following codestyle.cssOffice hours:


*{ frame size: border frame; Font family: -apple system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, chantell, "fira sans", "droid sans", "helvetica Neue", Arial, sans serif; Font size: 16px; -webkit-font-smoothing: smoothing; -moz-osx-font-smoothing: greyscale;}body {background color: #435165;}.login {width: 400px; background color: #ffffff; box shadow: 0 0 9px 0 rgba(0, 0, 0, 0,3); margin: 100px auto;}.login h1 { text-align: center; Color: #5b6574; Font size: 24px; padding: 20px 0 20px 0; bottom border: 1px solid #dee0e4;}.loginform { display: flex; flexible sleeve: sleeve; justify-content: center; padding-top: 20px;}.login-form-label { display: flex; justify-content: center; Align elements: center; Width: 50px; Height: 50px; Background color: #3274d6; color: #ffffff;}.login-form-input[type="password"], login-form-input[type="text"] { width: 310px; Height: 50px; border: 1px fixed #dee0e4; bottom margin: 20px; padding: 0 15px;}.login form input [type="submit"] { width: 100%; Padding: 15px; top margin: 20px; Background color: #3274d6; limit: 0; cursor: pointer; font weight: bold; Color: #ffffff; transition: background color 0.2 s;}.loginforminput[type="submit"]: hover { backgroundcolor: #2868c7; transition: background color 0.2s;}

We need to paste our stylesheet into oursindex.htmlfile, so we need to add the following code to the header section:


<link href="style.css" rel="stylesheet" type="text/css">

And now when we update thoseindex.htmlpage in our web browser, our login form will look more attractive:


Secure login system with PHP and MySQL (2)

This looks so much better! Let's collapse the elements of the form so we can better understand what's going on.

  • The picture"We have to use both."PlotjPostAttributes, the erPlotThe attribute is defined in the authentication file. When the form is submitted, the form data is sent to the authentication file for processing. additionallyMethoddeclares himself asPostas this allows us to process the form data using the POST request method.
    • Input (text/password)— We need to name our form fields so the server can recognize them. The attribute valueNamewe can declare asusernamewhich we can use to get the post variable in our authentication file to get the data, for example:$_POST['username'].
    • enter (send)— After submitting the form, the data is sent to our authentication file for processing.

3. Database creation and table configuration

For this part, you need to access your MySQL database usingphpMyAdmino Your favorite MySQL database management application.

Follow the instructions below when using itphpMyAdmin.

  • Navigate to:http://localhost/phpmyadmin/
  • click noDatabaseleadership at the top
  • Lowcreate database, Registrationphploginin the text field
  • Selectutf8_general_cilike the snack
  • give clickCry

You can use your own database name, but for this tutorial we'll usephplogin.

What we need now is abillsbecause it stores all the accounts (users, passwords, emails, etc.) registered in the system.

In the left pane, click the database (phplogin) and run the following SQL statement:


CREATE TABLE IF NO EXISTS `accounts` (`id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY(`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULTS=utf8;INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', ' $2 y$10$SfhYIDtn.iOuCW7zfoFLuuZHX6lja4lF4XA4JqNmpiH/.P3zB8JCa', '');

AnphpMyAdminit should look like this:

(Video) Register the user in the database | PHP and MySQL secure login system | Part 1


Secure login system with PHP and MySQL (3)

The above SQL statement code creates the accounts table with the columnsI WOULD GO,username,Clave, YouEmail.

The SQL statement enters a test account with the username:Test, and the password:Test🇧🇷 The test account is used for testing purposes to ensure our login system is working correctly.

4. User authentication with PHP

Now that we have our database set up, we can start programming with PHP. Let's start with the authentication file that will process and validate the form data that we send from oursindex.htmloffice hours.

edit theauthenticate.phpfile and add the following:


<?phpsession_start();// Change your connection information.$DATABASE_HOST = 'localhost';$DATABASE_USER = 'root';$DATABASE_PASS = '';$DATABASE_NAME = 'phplogin';// Try logging in with the information above connect to . $con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);if ( mysqli_connect_errno() ) { // If there is an error connecting, stop the script and show error.exit('Error connecting Connect to MySQL : ' .mysqli_connect_error());}

First the code will log you in as this allows us to store account details on the server and is later used to remind users that they are logged in.

The connection to the database is mandatory. Without them, how can we retrieve and store information about our users? So we need to make sure we update the variables to reflect our MySQL database credentials.

Add below:


// Now we check if the login form data has been submitted, isset() checks if the data exists.if (!isset($_POST['username'], $_POST['password']) ) { // The data, that should be sent could not be retrieved. exit('Fill in the username and password fields!');}

The code above ensures that the form data is present. However, if the user tries to access the file without submitting the form, a simple error is thrown.

Add below:


// Preparing our SQL, preparing the SQL statement prevents SQL injection. i = int, b = blob, etc.), in our case the username is a string, so we use "s"$stmt->bind_param('s', $_POST['username']); $stmt-> execute( );// Stores the result to check if the account exists in the database. $stmt->store_result();$stmt->close();}?>

The code above prepares the SQL statement that selects theI WOULD GOjClaveColumns of the Chart of Accounts. In addition, it will forceusernameto the SQL statement, execute it and save the result.

After the following line:




if ($stmt->num_rows > 0) {$stmt->bind_result($id, $password);$stmt->fetch(); // The account exists, now let's check the password. // Note: Remember to use password_hash in your log file to store the hashed passwords. if (password_verify($_POST['password'], $password)) { // Verification successful! The user is logged in! // create sessions so we know the user is logged in, they basically behave like cookies but remember the data on the server.session_regenerate_id();$_SESSION['loggedin'] = TRUE;$_SESSION[ ' name'] = $_POST['username'];$_SESSION['id'] = $id;echo 'Welcome'. $_SESSION['Name'] . '!';} else { // Wrong password echo 'Wrong username and/or password!';}} else { // Wrong username echo 'Wrong username and/or password!';}

First we need to check if the query returned any results. If heusernamedoes not exist in the database, so there would be no results.

If the username exists, we can associate the results with both$-IDj$passwordvariables

Then we checked the password with thePassword verifiedProfession. Only passwords created with thehash_passwordthe function will work.

If you don't want to use password encryption methods, just replace the following code:


if (password_verify($_POST['password'], $password)) {



if ($_POST['password'] === $password) {

However, I do not recommend removing hashes because if your database is exposed in any way, all passwords stored in the accounts table will also be exposed. In addition, the user has a sense of privacy knowing that their password is encrypted.

After successful user authentication, session variables are initialized and persist until destroyed on logoff or when the session expires. These session variables are stored on the server and associated with a session ID stored in the user's browser. We use these variables to determine whether the user is logged in or not and to associate the session variables with the results from our retrieved MySQL database.

did you know alreadyThe session_regenerate_id() function helps prevent session hijacking by regenerating the user's session ID, which is stored on the server and as a cookie in the browser.

(Video) Secure Login system using PHP with MYSQL database

The user cannot change the session variables in their browser and should therefore not worry about this issue. The only variable they can change is the encrypted session ID, which is used to associate users with sessions on the server.

Now we can test the login system and make sure the authentication works correctly. navigate tohttp://localhost/phplogin/index.htmlin your browser.

Enter a random username and password and click the Sign In button. It should produce an error similar to the following:


Secure login system with PHP and MySQL (4)

Don't worry, it's not broken! If we navigate back to our registration form and enterTestFor the Username and Password fields, the authentication page looks like this:


Secure login system with PHP and MySQL (5)

If you get an error, check your code to make sure you haven't missed anything, or make sure theTestAccount exists in your database.

5. Creation of the homepage

The home page is the first page our users see when they log in. You can only access this page if you are logged in, otherwise you will be redirected to the login page.

edit thehome.phpfile and add the following code:


<?php// We need to use sessions, so you should always start sessions with the following code.session_start();// If the user is not logged in, redirect to the login page...if (!isset ($ _SESSION ) [ 'logged in'])) { header('Location: index.html');exit;}?>

Basically, the code above checks if the user is logged in; Otherwise you will be redirected to the login page. remember the$_SESSION['connected']variable in which we have definedauthenticate.phpLegal action? This allows us to determine whether users are logged in or not.

Now we can add some HTML to our homepage. Under the closing tag, add the following code:


<!DOCTYPE html><html><head><meta charset="utf-8"><title>Seitenanfang</title><link href="style.css" rel="stylesheet" type="text/ css "><link rel="stylesheet" href=""></head><body class="loggedin"> <classe de navegação ="navtop"><div><h1>Título do site</h1><a href="profile.php"><i class="fas fa-user-circle"></i>Perfil</a >< a href="logout.php"><i class="fas fa-sign-out-all"></i>Fechar sessão</a></div></nav><div class="content "> < h2>Página inicial</h2><p>Bem-vindo de volta, <?=$_SESSION['name']?>!</p></div></body></html>

The code above is the template for our home page. On this page the user will find a welcome message along with their name.

We need to add CSS to the homepage. Add the following codestyle.cssOffice hours:


.navtop {background-color: #2f3947;alto: 60px;ancho: 100%;borde: 0;}.navtop div {pantalla: flex;margen: 0 automatic;ancho: 1000px;alto: 100%;}.navtop div h1, .navtop div a {display: inline-flex;align-items: center;}.navtop div h1 {flex: 1;font-size: 24px;padding: 0;margin: 0;color: #eaebed;font- Peso: normal;}.navtop div a {Padding: 0 20px;Textdekoration: nenhum;Farbe: #c1c4c8;Schriftstärke: fett;}.navtop div a i {Padding: 2px 8px 0 0;}.navtop div a :hover {color: #eaebed;}body.loggedin {background-color: #f3f4f7;}.content {width: 1000px;margin: 0 auto;}.content h2 {margin: 0;padding: 25px 0;font-size : 22px;Borda inferior: 1px sólido #e0e0e3;color: #4a536e;}.content > p, .content > div {box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.1);margen: 25px 0 ;preenchimento: 25px;cor de fundo: #fff;}.content > p table td, .content > div table td {preenchimento: 5px;}.content > p table td:first-child, .content > div table td : Primer hijo {peso da fonte: negrito;cor: #4a536e;padding-direita: 15px;}.conte nt > div p {padd ing: 5 px;margen: 0 0 10px 0;}

Now that we have our home page set up, we can redirect our users fromauthenticate.phpFile for our homepage, editauthenticate.phpand replace the following line of code:


echo 'Welcome'. $_SESSION['Name'] . 🇧🇷



header('Location: home.php');

If you sign in with the test account, you should see something like this:


Secure login system with PHP and MySQL (6)

This is a pretty basic home page. You can customize it however you like now that you understand how it works.

6. Creation of profile page

The profile page displays the logged-in user's account information.

edit theprofile.phpfile and add the following code:

(Video) How To Create A Login System In PHP For Beginners | Procedural MySQLi | PHP Tutorial


<?php// We need to use sessions, so you should always start sessions with the following code.session_start();// If the user is not logged in, redirect to the login page...if (!isset ($ _SESSION ) [ 'logged in'])) {header('Location: index.html');exit;}$DATABASE_HOST = 'localhost';$DATABASE_USER = 'root';$DATABASE_PASS = '';$DATABASE_NAME = 'phplogin' ; $ con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);if (mysqli_connect_errno()) { exit('Failed to connect to MySQL: ' . mysqli_connect_error());}// We don't have the password or the email addresses stored in sessions so that we can retrieve the results from the database. ID to retrieve the account information. $stmt->bind_param('i', $_SESSION['id']);$stmt->execute();$stmt->bind_result($password, $email);$ stmt->find();$stmt ->Close();?>

The code above retrieves additional account information from the database, like before with the homepage, we don't need to connect to the database since we are retrieving data stored in sessions.

We will fill out all user account information and therefore need to retrieve theClavejEmaildatabase columns. we don't need to restusernameÖI WOULD GOColumns because we stored them in session variables declared inauthenticate.phpoffice hours.

Add the following code after the closing tag:


<!DOCTYPE html><html><head><meta charset="utf-8"><title>Profilseite</title><link href="style.css" rel="stylesheet" type="text/ css "><link rel="stylesheet" href=""></head><body class="loggedin"> <class navigation ="navtop"><div><h1>Seitentitel</h1><a href="profile.php"><i class="fas fa-user-circle"></i>Profil</a>< a href="logout.php"><i class="fas fa-sign-out-alt"></i>Abmelden</a></div></nav><div class="content ">< h2>Profilseite</h2><div><p>Ihre Kontodaten sind unten:</p><table><tr><td>Benutzername:</td><td> <?=$_SESSION['name ']?></td></tr><tr><td>Passwort:</td><td><?=$password?></ td></tr> <tr><td>E-Mail: </td><td><?=$email?></td></tr></table></div></div> </body></ html>

A simple design that fills in the account information. If you navigateprofile.phpfile looks like this:


Secure login system with PHP and MySQL (7)

Remember that passwords are encrypted, so you cannot see the decrypted password unless you create a new session variable and store the password in itauthenticate.phpoffice hours.

7. Creating the logout script

Creating the logoff script is easy. All you have to do is destroy the sessions declared in the authentication file.

edit theexit.phpfile and add the following code:


<?phpsession_start();session_destroy();// Redirect to login page:header('Location: index.html');?>

Initialize the sessions, destroy them and redirect the user to the login page. We use sessions to determine if the user is logged in or not. So if you remove them, the user will not be logged in.


You should now have a basic understanding of how a login system works with PHP and MySQL. You can use the source code freely and integrate it into your own projects.

The next step is to create a registration system for visitors to register.

Don't forget to follow us and share the article as this will help us to create future tutorials and update existing content with new features.

Next tutorial in this series:Secure registration system with PHP and MySQL

If you would like to support us, please consider purchasing the enhanced secure login and registration system below as it will greatly help us to create more tutorials and keep our website running. The advanced pack includes improved code and more features.



see more details

Source code

Database SQL file

Secure login and registration system

Edit homepage, profile and profile pages

Account Activation Feature

reminder function


PDO, MVC OOP and basic versions

(Video) Secure Login Form Authentication System (Cookies, Sessions, Token, PDO) PHP & MySQL Tutorial Part 1

administration menu

Plugin: I forgot my password

Add-on: Brute-Force-Schutz

Add-on: CSRF-Schutz

Add-on: Two-Factor Authentication

Addition: Captcha

Responsive design (mobile friendly)

SCSS file

commented code

Free updates and support (minor issues)

operation manual

Bonus: tutorial source code



Package (save 53%)



see more details

Secure login and registration system

shopping cart system

CRUD application

ticket system

gallery system

event calendar system

Voting and voting system

comment system

evaluation system

Contact form


Newsletter and mail system

Access to future scripts


(Video) Secure Login system using PHP with MYSQL database - Part #2 Preventing xss attacks


1. Secure Login & signup system using PHP with MYSQL database - Part #1
(The Coding Hax)
2. Registration Form - Secure PHP Authentication System from Scratch Ep. 1
(Code Break)
3. Secure Admin Login Page in PHP
4. How To Create A OOP PHP Login System For Beginners | OOP PHP & PDO | OOP PHP Tutorial
(Dani Krossing)
5. Secure Login System with PHP and MySQL - mistacode
(Pukka Media)
6. Simple signup and login system with PHP and Mysql database | Full Tutorial | How to & source code
(Quick Programming)


Top Articles
Latest Posts
Article information

Author: Mr. See Jast

Last Updated: 26/09/2023

Views: 6075

Rating: 4.4 / 5 (55 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.