How to Create Secure User Login Script in PHP PDO - Free Download
  • Home
  • PHP

How to Create Secure User Login Script in PHP PDO – Free Download

This is Secure Login Script System, which allows you to login with username and email simultaneiously. And creates the session with security measures. And one more important feature about this Login system is, if the logged in user tries to access login page or register page he will be redirected to dashboard or members area page. Because once the user is logged in, he shouldn’t be able to access the login or register pages.

As I promised in the title, Download Secure User Login Script in PHP PDO, You can Download it for Free and Also You can Watch the Complete Video Tutorial for Free.

Download Complete Code of User Login Script in PHP for Free

Here I’ve created a free video series for you watch and learn, how to create a secure user login/registration/reset password system. And it’s 4 videos
First video is about setting up the project
Second Video is Secure User Registration System
Third Video is Secure User Login System
Fourth Video is Reset Password System with reset token

At the end of the video I’ve added a demo for the most advanced user registration & login system with a lot security features like limiting logins to stop brute force attacks and activity tracker for tracking all the user activity with in the portal and a lot of features, after seeing the demo video you will understand.

1. Preparing HTML Form & Database

1 a. Explaning About table structure

Here is the SQL code of users table, you can use this code to create the table with the required columns. It contains id column with PRIMARY KEY and AUTO INCREMENT, username & email columns for storing usernames and emails of registered users

Password column for storing strong password hashes of registed user.

With these three columns username, email and password. We will check the user account.

This is the brief description of users table.

1 b. Connecting to Database

Create a file in includes directory and save it as connect.php, use this code on this file. This code connects to database with the database user login credentials provided, use the database name that you created in the previous step. This is PDO style of connecting to database. We will include this file in other PHP files for connecting to database using this connect.php repeatedly. We will use this file only once on each file, for that I’m going to use require_once PHP function.

1 c. Adding Reusable Template Files

These Reusable Template Files, I’m using them from this HTML code => Login, Register, Reset Password HTML Forms


This header.php file contains head section of the HTML code till opening div tag inside body section.


In footer.php is the code from closing div tag to end of the HTML code.

Ater loding these 2 template files, I’m going to add the login from.

1 d. Adding User Login form HTML Code

Here I’m using header & footer template files along with connect.php file for connecting to database with PHP PDO.

Between these Reusable template files is the simple bootstarp styled form with User Name/Email & Password input fields. After submitting the form with submit button, this submitted data will be checked in users table. If any row matches with this User Name/Email & Password combination, User will be logged into the System.

2. Adding Form Validations

Before procedding furthur in our User Login System, we should add the PHP Form validations to check the user inputs. Still we can use HTML Form Validations, but that is not that secure to rely on because it is browser based validation, any one with little bit of coding knowldege can modify the validation from browser. For that purpose I strongly suggest you to use PHP Form Validations in your code.

Here I’m checking the submitted input field values are not empty, I’m adding this check for User Name/Email Field & Password Field. That means I’m making the submission as required for these fields from server side programming.

Before even proceeding with PHP Form Validations, we should check the post super global that is to check wether the form is submitted or not?

With the above code we make the input field as required.

3. Displaying Form Validation Errors

With the above form validations code, we have checked the form fields for validations. That is input field required validation. In case of errors, I’ve created an errors array to store all these error messages.

Now it’s time to display these error messages to user by looping through errors array and displaying each item with bootstrap alert box danger styling.

Before displaying the error message, we should check whether the errors array is not empty. Then only I’ll proceed with displaying the errors.

4. Displaying Form Data on Failed Form Submission

In case of errors, form page will be reloaded again and again till there are no errors. If we are not returing the values and displaying them on the form, It is difficult for a user to enter the same input fileds value again and again, if that is happening user will try for couple of times may be if he has good patience after that he abandons the form and website all together. For avoiding this kind of situations with user, we should return the values on the form input fields in case of errors. So, that user can update the values in the form and submitts the form again.

To return and display the submitted values on the form, we will check if the post super golbal value with the input fields name. If it’s set and not empty then we will display in the form field with in input fileds value attribute.

Here I’m returning User Name / Email input fields value. In case of error or incorrect login credentials user don’t have to fill the form again, user can update the user name / email input field value and can submit the form. For password input field user has to enter it again because user can’t reverify these password input fields value as they are hidden that’s default behaviour of password input fields.

5. Adding CSRF Protection

CSRF TOkens adds an extra layer of protection to our forms by protection it from attackers submitting the requests. It checks for the CSRF token is valid that is submitted through the form, otherwise it will returns token mismatch error.

If the user is authentic user and submitting from the same page, then only requested will be accepted and User Registration will be completed successfully.

There are three steps to add add CSRF Protection in our forms => Checkout this article for learning about CSRF Token Protection

5 a. Creating CSRF Token

CSRF Token is a random string generated with multiple PHP functions. To generate CSRF Token, here I’m using these three PHP functions rand, uniquid, md5 functions. By combining these three functions, I’m generating a CSRF Token and assigning that into a variable, also storing this CSRF token in session. We will use this CSRF Token session, in next step while checking the token

For added layer of security, I’m storing the time when the form page is loaded. Based on this time we can check the token, If the form is submitted beyond certain amount of time, we can reject the request.

5 b. Adding CSRF Token

Adding CSRF Token is simple, in previous step we have created the CSRF Token. This token should be added to the form, for this we will add it as hidden input field. While submitting the form, this CSRF token also will be sent with the request in POST super gobal.

5 c. Checking CSRF Token

Now it’s time to check the CSRF Token, If the csrf token is set we will compare csrf token submitted through form and csrf token value stored in session. If it doesn’t match, we will return an error message.

Next, we should chcek the CSRF Token Time validation. That is if the page was loaded few days before and submitting the form after few days, then we shouldn’t process that request. For blocking this kind of requests, I’m adding CSRF Token Time Validation.

First of all, I’m setting the maximum time that we will allow the request. Here I’m setting it as 24 hours in seconds. Then we will check the present time stamp with csrf token time added to maximum time that we set earlier. If it’s with in the range we will allow the request else we reject the request and return an error message.

6. Adding Login Logic

And the final step is Logging in users, after all the above steps like Form validations, CSRF Token Protection, we will check the submitted User Login credentials with users table records using PHP PDO’s simple SELECT SQL query.

Checkout out this article, if you want to learn more about SELECT Operation with PHP PDO

Firstly, I’m checking whether there are any errors. If no errors we will proceed with SELECT Operation with named array binding in PHP PDO.

6 a. Checking User Exists

With is SELECT SQL query, we will check if the sumbitted email exists is our users database. If it exists it will return 1 as number of rows, because earlier while creating the database table we used unique key for username and email. So one email or username will be stored only once.

If the number of rows equals to one, then we will procedd to compare the password hash with submitted password.

If there are no records with the submitted email id, then we will return an error.

6 b. Comparing the Password

From the above step, if the number of records count equals to one. Then we will compare the plain text password with password hash from database that we fetched from previous step.

For comparing the password, I’m using password_verify function. If it return true, then we will create the session and redirect the user to members area page. Otherwise, we will return an error message.

6 c. Enabling Login with User Name & Email

Instead of allowing users only with email address, I’ll update this to work with username and email address. User can enter valid user name and password combination or a valid email and password combination.

7. Creating Secure Session

To complete the final step in User Login process, creating the session. While comparing the passwords, if it returns true. Then I’m regenerating the session id and creating the session with user information.

After creating the session, I’m redirecting the use to dashboard page.

8. Logout

After login, there should be a way to logout the user from system. For logging out user I’m using simple function session_destroy.

Use this code and save it as logout.php file, link to this page on all logout links.

9. Checking Login on Admin Dashboard Page

Save this code into check-login.php file. We will include this file on the authenticated pages section, those pages will be accessed by logged in users only.

Here in this code, I’m checking the sessions created in the previous step. If any one of the value doesn’t exist, I’m redirecting the suer to login page.

User has to login again, with his/her login credentials.

10. Checking If LoggedIn on Login & Register Pages

If the User is already LoggedIn, then user shouldn’t be able to access the login page or register page for that reason, I’m adding this code.

Save this code into if-loggedin.php file. We will include this file login.php and register.php files.

I’m including this file only on login.php & register.php files, still I’m checking the file current pages file name with basename and PHP_SELF server variable.

If it’s equal to login.php or register.php, then I’m checking the session. If the session is set, then the user will be redirected to dashboard page. Otherwise, user will stay on the same login or register page.

Complete Code

You can create the files by combining above snippets of code, For any reason if you are not able to combine those files. You can access the complete coding files from here.

Download Complete Code of User Login Script in PHP for Free

What are the things covered to secure the login system

This Login System is more secure and I’ve implemented these security measures to make it more secure.


First one is, Here I’m using PHP PDO for connecting to database and for other database operations. PHP PDO helps to secure our application from SQL Injections.


Second one is, Using CSRF Tokens. CSRF Tokens helps us to protect form submissions, that is only the authentic and valid form submissions will only be accepted. Third party form submissions without CSRF Tokens won’t be accepted.

Secure Session

And the third security measure is creating Secure Session by regenerating session id with regenerate_session_id PHP function. That means session id before login and after login are different.

If you want to add anyother security measures, please let me know through the comment form.

What other things can be done to make it more secure

In addition to the above Security measures, you can add more security by adding these features. These features only available on paid script.

Brute Force Attacks

A hacker can hack user account by trying multiple username and password combinations, this is called brute force attacking & dictionary attack.

We should stop these attacks to create more secure application.

Limiting Login attempts

We should Limit the number of login attempts that a user can try, if he is having multiple failed login attempts. With this we can eliminate the abusing users and the users who are using unnecessary server resources.

Logging user Login attempts

We should log the user Login attempts with their ip address, both successful and failed login attempts. So that we can use this login attempts information while Limiting the Login attempts and also in eliminating Brute Force Attacks.

Conclusion to the User Registration System

I hope this User Login System is helpful to you, now you can use this Login System in your web applications. If you have any queries, let me know through the comment form below.

If you need additional features, Download the source code of the project that you have seen in the demo video with the form below.

If you need any customisations, Send me an Email on the download email you received with your requirement (customisation is a paid service based on your requirement).

user dashboard according to their activity in php 7 and pdo php pdo login script pdo signup thst automaticslly logs in user pdo secure login 2019 pdo login admin pdo admin registration script multi login php pfo how to prepare on admin dashboard in php coding how to create multi level log in and registration with log in attempts and PDO in PHP 2019 how to construct a secure user name for login
Vivek Vengala

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: