Building a Simple PHP Login System

In today’s digital age, building a login system is a crucial part of many web applications. Whether you’re creating an e-commerce site, a social network, or a simple blog, allowing users to register and authenticate themselves is an essential feature. PHP is a popular server-side scripting language that is widely used for building dynamic websites, and it provides a number of features that make it well-suited for building login systems. In this tutorial, we’ll go through the steps required to build a simple PHP login system that allows users to register, log in, and log out. Please like and follow!
Step 1: Setting up the database
The first step in building a PHP login system is to create a database that will store user login credentials. We’ll be using MySQL in this tutorial, but you can use any other database management system of your choice. Here’s an example of the SQL code to create a simple users
table in MySQL:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
This creates a table with three columns: id
, username
, and password
. The id
column is an auto-incrementing primary key, and the username
and password
columns will store the user’s login credentials.
Step 2: Creating the login form
Next, we’ll create a simple HTML form that will allow users to enter their login credentials. Here’s an example of what the login form might look like:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
This form contains two input fields for the username and password, as well as a submit button. When the user submits the form, it will send a POST request to the login.php
script, which we’ll create in the next step.
Step 3: Processing the login form
Now, we’ll create the PHP script that will process the login form data and authenticate the user. Here’s an example of what the login.php
script might look like:
<?php
// Start a new session
session_start();
// Connect to the database
$dsn = "mysql:host=localhost;dbname=mydatabase";
$username = "myusername";
$password = "mypassword";
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Process the login form
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Get the username and password from the form
$username = $_POST['username'];
$password = $_POST['password'];
// Query the database for the user
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
// Check if the password is correct
if ($user && password_verify($password, $user['password'])) {
// Set the session variables
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// Redirect to the home page
header('Location: index.php');
exit();
} else {
// Invalid login credentials
$error = "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<?
// Show any login errors if (isset($error)) { echo "<p>{$error}</p>"; } ?>
<form method="post" action="login.php"> <label for="username">Username:</label> <input type="text" name="username" required><br><br> <label for="password">Password:</label> <input type="password" name="password" required><br><br> <button type="submit">Login</button> </form> </body> </html>
Let’s go through this script step-by-step:
- First, we start a new session using
session_start()
. This allows us to store user information across multiple page requests. - Next, we connect to the database using PDO. Replace
mydatabase
,myusername
, andmypassword
with your own database name, username, and password, respectively. - Inside the
if ($_SERVER['REQUEST_METHOD'] == 'POST')
block, we retrieve the username and password from the login form using$_POST
. - We then query the database for the user with the specified username using a prepared statement. If a matching user is found, we verify the password using
password_verify()
. This function compares the submitted password with the hashed password stored in the database. - If the password is correct, we set the
user_id
andusername
session variables and redirect the user to the home page usingheader()
. - If the password is incorrect or the user is not found, we display an error message.
Step 4: Restricting access to protected pages
Now that we have a working login system, we can use it to restrict access to pages that should only be visible to logged-in users. To do this, we’ll add some code to the top of each protected page that checks whether the user is logged in. Here’s an example:
<?php
// Start the session
session_start();
// Redirect to the login page if the user is not logged in
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Protected Page</title>
</head>
<body>
<h1>Welcome, <?php echo $_SESSION['username']; ?>!</h1>
<p>This page is only visible to logged-in users.</p>
<a href="logout.php">Logout</a>
</body>
</html>
This code starts a session and then checks whether the user_id
session variable is set. If the user is not logged in, the script redirects them to the login page using header()
. If the user is logged in, the script displays the protected page.
Step 5: Logging out
Finally, we need to add a way for users to log out of the system. This is easy to do with a simple logout.php
script:
<?php
// Start the session
session_start();
// Unset all session variables
$_SESSION = array();
// Destroy the session
session_destroy();
// Redirect to the login page
header('Location: login.php');
exit();
?>
This code unsets all session variables and destroys the session. It then redirects the user to the login page.
In this tutorial, we’ve learned how to build a simple PHP login system that allows users to authenticate themselves and access protected pages. We’ve also learned how to use PDO to connect to a MySQL database, and how to store and retrieve session variables. You can customize this login system to fit your own needs, such as adding additional user information to the database or creating different types of users with different access levels. You can also improve the security of the system by adding password strength requirements, using two-factor authentication, or implementing password reset functionality.
Lyron Foster is a Hawai’i based African American Author, Musician, Actor, Blogger, Philanthropist and Multinational Serial Tech Entrepreneur.