Login System in PHP

Introduction

In today’s digital world, almost every website requires user authentication. Whether it’s a social media platform, an e-commerce store, or an online learning website, a login system plays a crucial role in securing user data and providing personalized experiences.

A login system in PHP ensures that only authorized users can access specific resources. PHP is a powerful server-side scripting language.

In this article, we will explore how a login system works in PHP, its importance, syntax, examples, and best practices.

What is Login System in PHP?

A Login System in PHP is a mechanism that authenticates users by verifying their credentials (such as username/email and password) against stored data in a database.

When a user enters login details:

  1. The data is sent to the server.
  2. PHP processes the input.
  3. The credentials are checked against the database.
  4. If matched, access is granted; otherwise, access is denied.

The login system usually works with:

  • PHP (backend logic)
  • MySQL (database)
  • HTML/CSS (frontend interface)
  • Sessions (to maintain user login state)

Syntax

Below is the basic structure of a login system in PHP:

1. Database Table Example


CREATE TABLE users (
   id INT AUTO_INCREMENT PRIMARY KEY,
   username VARCHAR(50),
   email VARCHAR(100),
   password VARCHAR(255)
);

2. HTML Login Form


<form method="POST" action="login.php">
   <input type="email" name="email" required>
   <input type="password" name="password" required>
   <button type="submit">Login</button>
</form>

3. PHP Login Logic (login.php)


session_start();
$conn = mysqli_connect("localhost", "root", "", "test_db");
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);
if($user && password_verify($password, $user['password'])) {
   $_SESSION['user'] = $user['email'];
   echo "Login Successful";
} else {
   echo "Invalid Email or Password";
}

Example

Let’s create a simple working login system step by step.

Step 1: Register User (store hashed password)


$conn = mysqli_connect("localhost", "root", "", "test_db");
$email = "test@example.com";
$password = password_hash("123456", PASSWORD_DEFAULT);
$sql = "INSERT INTO users (email, password) VALUES ('$email', '$password')";
mysqli_query($conn, $sql);

Step 2: Login Page


<form method="POST" action="login.php">
   <input type="email" name="email" required>
   <input type="password" name="password" required>
   <button type="submit">Login</button>
</form>

Step 3: Dashboard Page (protected)


session_start();
if(!isset($_SESSION['user'])) {
   header("Location: login.html");
   exit();
}
echo "Welcome " . $_SESSION['user'];

Step 4: Logout


session_start();
session_destroy();
header("Location: login.html");

This is a complete basic login system using PHP and sessions.

Real-Life Example

Think about websites like:

  • Online shopping platforms (Amazon, Flipkart)
  • Social media apps (Facebook, Instagram)
  • Learning platforms (Udemy, Coursera)

When you log in:

  • Your credentials are verified.
  • A session is created.
  • You are redirected to your dashboard.

For example, on an e-commerce website:

  • Users log in to track orders.
  • Save addresses and payment methods.
  • Access order history.

Without a login system, none of this personalization would be possible.

Common Mistakes

1. Storing Passwords in Plain Text

❌ Wrong:


$password = "123456";

✔️ Correct:


$password = password_hash("123456", PASSWORD_DEFAULT);

2. Not Using Prepared Statement

Using direct queries can lead to SQL Injection.

❌ Wrong:


$sql = "SELECT * FROM users WHERE email='$email'";

✔️ Correct:


$stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
$stmt->bind_param("s", $email);
$stmt->execute();

3. Not Starting Session

Forgetting session_start() will break login functionality.

4. Weak Password Validation

Allowing simple passwords reduces security.

5. Not Sanitizing Input

User input should always be validated and sanitized to prevent attacks.

6. No Logout Functionality

Users should always have a secure way to log out.

Conclusion

A login system in PHP is a fundamental feature for modern web applications. It ensures secure user authentication, protects sensitive data, and enhances user experience through personalization.

By using PHP sessions, password hashing, and proper validation techniques, developers can build a secure and efficient login system.

Whether you are building a small website or a large application, implementing a secure login system is essential.

Login System in PHP – Interview Questions

Q 1: What is a login system in PHP?
Ans: A login system authenticates users by verifying credentials and allowing access to secured resources.
Q 2: What is session in PHP?
Ans: A session is used to store user data across multiple pages after login.
Q 3: Why use password_hash()?
Ans: It securely hashes passwords to protect them from being exposed.
Q 4: What is SQL Injection?
Ans: A security vulnerability where attackers insert malicious SQL queries into input fields.
Q 5: How do you prevent SQL Injection?
Ans: By using prepared statements and input validation.
Q 6: By using prepared statements and input validation.
Ans: Session: Stored on server
Cookie: Stored on user browser
Q 7: What happens after successful login?
Ans: User session is created and user is redirected to a protected page.
Q 8: How to check if user is logged in
Ans:
 if(isset($_SESSION["user"])) 

Related PHP Tutorials