Create Simple Login Script in PHP and MySql

This is a simple login system in PHP and MySql. Most of the web applications it is necessary to have an authentication system. Latest frameworks such as Laravel, Symfony have bundles(modules) to do this job with the most advanced secure method. But this tutorial is intended for a beginners who wants to understand an authentication system in the simple language.

User authentication in php

  • Creating the form in HTML
  • Posting the form values
  • Sanitising the input
  • Connecting to database
  • Verifying the form values against the database
  • If login is successful, then redirect to the dashboard page


First, we have to create a database for our application. After that, we are creating a database table called users. If you are on the server you have to do MySQL login before doing this and run the below query.


This would be our master file as all the operations take place in this file. As you can see I have used Bootstrap to avoid the hassle of creating a new template. I have a form in this two enter the email and password. In the first section, it’s verifying the input and stripping all the tags from it to prevent any XSS attack. There are plenty of libraries that doing this. I just demonstrated as a simple example. Next, if all the form fields are validated its moving to the database validation process. Here I have PDO for the database interactions as its the best approach for secure applications. Bcrypt is used for the password hashing, so you just want to use the below code for password hash.

password_hash("samplepass123", PASSWORD_BCRYPT);

For the verification you have to use

password_verify($password, $hashedPwdDB)
. You can see the method used in this example.


Its the database connection for our application. We include this file in all PHP files to connect to the database.  As I said earlier we use PDO to secure the application from SQL injection attacks.


It’s just a dashboard page that welcomes the logged in user.


This page is to destroy the session we set in the login page. So once the session destroyed the user will not have access to the dashboard page.

In addition to this, I have added a file called insert_user.php to add a user. You can modify this file to add your new user and test the script. You can read this article for how to create user register form in PHP

Download the file in my GitHub repository


Editorial Staff

Editorial Staff at tutsplanet is a dedicated team to write various tutorial articles.