How to Create a Secure Login Script with MySQLi in PHP

In this Tutorial, we will be going over how to create a secure login script in PHP and MySQLi. This is a great way for you to have an additional security measure on your website that protects user information from being stolen. In the process of creating this script, we will go through how to set up a database connection with MySQLi and other SQL statements needed for the script.

Create a MySQL database

As an administrative user, log into your database (usually root). Once you are in, create a new database and call it whatever you want.

After creating the MySQL Database, we can go ahead and set up our table for storing user information such as “username”, “password” etc. We will name this table users:

Creating The Login Script With PHP & MySQLi

Now that we have all of our data prepared to be stored within our script, let’s move forward with how we actually present everything on the page and handle the login process. To do so, I’ve created an index file which is typically what people start with when learning how to make a website from scratch (with no coding knowledge). Below is my code: 

<?php//Setting our database information define(‘DB_NAME’, ‘database-name’); define(‘DB_USER’, ‘username’); define(‘DB_PASSWORD’, ‘password’); $link = mysqli_connect( DB_HOST, DB_USER, DB_PASSWORD, DB _NAME); if (mysqli_ connect_errno()){ echo “Failed to connect to MySQL: (” . mysqli_connect_error() . “)”; } ? >

Once we have this script saved as index.php within the same directory where all of your other files are stored and the path is set correctly for any images used on the login form, we can start to create our HTML form.

The first step is to create a basic html skeleton for our login form: 

  1. We will need two input fields – one for the username and one for the password. We’ll also add a submit button so that the user can actually log in. The code looks like this: 
  2. Next, we’ll style our login form using some CSS. We want to make sure that both the input fields and the submit button are styled correctly and look like they belong on our page. The final code looks like this:
  3. Now that we have our login form all set up, we need to write some PHP code to process the user’s inputs and check whether or not they are logged in. If they are not, we’ll need to show them the login form so that they can enter their credentials.

The code for this is pretty simple – we just need to check whether or not the username and password fields have been filled in, and then compare the user’s input against the values stored in our database. If everything matches up, we’ll log the user in and display a success message. Otherwise, we’ll show an error message. Here’s what the code looks like:

That’s it! We now have a complete and functioning Secure Login Script using MySQLi in PHP. Enjoy!