Create a Powerful Login System with PHP in Five Easy Steps

Matt Mickiewicz
Share

In this guide, you’ll learn how to create a powerful login system with PHP! We’ll walk you through the process step by step, so you can have a secure and efficient login system for your website in no time.

PHP and Login Systems

PHP is a popular server-side scripting language that allows you to create dynamic web pages. One of the most common uses of PHP is to create login systems for websites.

A login system is essential for protecting sensitive information and providing personalized content to users. In this tutorial, we’ll create a simple yet powerful login system using PHP and MySQL.

We’ll cover the following steps:

Setting Up Your Environment

Before we start, make sure you have the following software installed on your computer:

  • a web server (such as Apache)
  • PHP
  • MySQL

You can use a package like XAMPP or WAMP to install all of these components at once.

Once you have everything set up, create a new folder in your web server’s root directory (such as htdocs for Apache) and name it login_system.

Creating the Database and Tables

First, we need to create a database and tables to store user information.

Open your MySQL administration tool (such as phpMyAdmin) and create a new database called login_system.

Next, create a table called users with the following structure:

CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This table will store the user’s ID, username, email, password, and the date the account was created.

Building the Registration Form

Let’s now create a registration form that allows users to sign up for an account.

Create a new file called register.php in your login_system folder and add the following code:

<form action="register.php" method="post">
  <label for="username">Username:</label> 
  <input id="username" name="username" required="" type="text" />
  <label for="email">Email:</label>
  <input id="email" name="email" required="" type="email" />
  <label for="password">Password:</label>
  <input id="password" name="password" required="" type="password" />
  <input name="register" type="submit" value="Register" />
</form>

This code creates a simple HTML form with fields for the username, email, and password. The form’s action attribute is set to register.php, which means the form data will be sent to the same file for processing.

Now, let’s add the PHP code to process the form data and insert it into the users table.

Add the following code at the beginning of your register.php file, before the declaration:

<?php if (isset($_POST['register'])) { 

// Connect to the database 
$mysqli = new mysqli("localhost", "username", "password", "login_system"); 

// Check for errors 
if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } 

// Prepare and bind the SQL statement 
$stmt = $mysqli->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $username, $email, $password); 

// Get the form data 
$username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; 

// Hash the password 
$password = password_hash($password, PASSWORD_DEFAULT); 

// Execute the SQL statement 
if ($stmt->execute()) { echo "New account created successfully!"; } else { echo "Error: " . $stmt->error; } 

// Close the connection 
$stmt->close(); $mysqli->close(); }

This code checks if the form has been submitted, connects to the database, and inserts the user’s information into the users table. The password is hashed using PHP’s built-in password_hash function for added security.

Building the Login Form

Next, let’s create a login form that allows users to sign in to their accounts. Create a new file called login.php in your login_system folder and add the following code:

<form action="login.php" method="post">
  <label for="username">Username:</label>
  <input id="username" name="username" required="" type="text" />
  <label for="password">Password:</label> <input id="password" name="password" required="" type="password" />
  <input name="login" type="submit" value="Login" />
</form>

This code creates a simple HTML form with fields for the username and password. The form’s action attribute is set to login.php, which means the form data will be sent to the same file for processing.

Let’s now add the PHP code to process the form data and authenticate the user. Add the following code at the beginning of your login.php file, before the declaration:

<?php session_start(); if (isset($_POST['login'])) { 

// Connect to the database 
$mysqli = new mysqli("localhost", "username", "password", "login_system"); 

// Check for errors 
if ($mysqli->connect_error) { die("Connection failed: " . $mysqli->connect_error); } 

// Prepare and bind the SQL statement 
$stmt = $mysqli->prepare("SELECT id, password FROM users WHERE username = ?"); $stmt->bind_param("s", $username); 

// Get the form data 
$username = $_POST['username']; $password = $_POST['password']; 

// Execute the SQL statement 
$stmt->execute(); $stmt->store_result(); 

// Check if the user exists 
if ($stmt->num_rows > 0) { 

// Bind the result to variables 
$stmt->bind_result($id, $hashed_password); 

// Fetch the result 
$stmt->fetch(); 

// Verify the password 
if (password_verify($password, $hashed_password)) { 

// Set the session variables 
$_SESSION['loggedin'] = true; $_SESSION['id'] = $id; $_SESSION['username'] = $username; 

// Redirect to the user's dashboard 
header("Location: dashboard.php"); exit; } else { echo "Incorrect password!"; } } else { echo "User not found!"; } 

// Close the connection 
$stmt->close(); $mysqli->close(); }

This code checks if the form has been submitted, connects to the database, and retrieves the user’s information from the users table. The password is verified using PHP’s built-in password_verify function. If the login is successful, the user is redirected to a dashboard.php page.

Securing Your Login System

To further secure your login system, you should implement the following best practices:

  • Use HTTPS to encrypt data transmitted between the client and server.
  • Implement CSRF (cross-site request forgery) protection using tokens.
  • Limit the number of failed login attempts to prevent brute-force attacks.
  • Store sensitive information — such as database credentials — in a separate configuration file outside the web server’s document root.
  • Regularly update your software, including PHP, MySQL, and your web server, to apply the latest security patches.

Conclusion

Congratulations! You’ve successfully created a powerful login system with login forms and secured your login system.