Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 40

PHP Login and Registration System (Full Code)

In this lesson: Secure PHP login and signup with MySQL, password_hash, sessions and validation — full source code step by step.

What we are building

A login system has four parts: a users table, registration (create an account), login (verify and start a session), and logout. Throughout, passwords are hashed and queries use prepared statements. This is the standard, secure pattern every real site follows.

💡 Two rules that keep it safe: hash passwords with password_hash, and use prepared statements for every query.

The users table

CREATE TABLE users (
    id       INT AUTO_INCREMENT PRIMARY KEY,
    email    VARCHAR(80) UNIQUE NOT NULL,
    password VARCHAR(255) NOT NULL
);

The UNIQUE email stops duplicate accounts. The password column is long (255) because a hash is much longer than the original password.

Registration

<?php
  $email = trim($_POST["email"]);
  $pass  = $_POST["password"];
  $hash  = password_hash($pass, PASSWORD_DEFAULT);

  $sql = "INSERT INTO users (email, password) VALUES (?, ?)";
  $stmt = $pdo->prepare($sql);
  $stmt->execute([$email, $hash]);
  echo "Account created";
?>
Account created

The password is hashed before saving, and the query uses placeholders. The database never sees the real password.

Login

<?php
  session_start();
  $email = trim($_POST["email"]);
  $pass  = $_POST["password"];

  $stmt = $pdo->prepare("SELECT id, password FROM users WHERE email = ?");
  $stmt->execute([$email]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);

  if ($user && password_verify($pass, $user["password"])) {
      $_SESSION["user_id"] = $user["id"];
      echo "Login success";
  } else {
      echo "Invalid email or password";
  }
?>
Login success

We look up the user by email, then password_verify checks the password against the stored hash. On success we save the user id in the session.

Protecting a page

<?php
  session_start();
  if (empty($_SESSION["user_id"])) {
      header("Location: login.php");
      exit;
  }
  echo "Welcome to your dashboard";
?>

Every page that needs a logged-in user checks the session first. If there is no user_id, it redirects to the login page.

Logout

<?php
  session_start();
  session_unset();
  session_destroy();
  header("Location: login.php");
?>

Logging out clears the session so the user is no longer recognised, then sends them back to the login page.

Common mistakes

  • Storing plain passwords. Always password_hash on register, password_verify on login.
  • Building SQL with input. Use prepared statements to block injection.
  • No UNIQUE email. Duplicate accounts slip in without it.
  • Not checking the session on protected pages. Anyone could open them directly.

Summary

  • A login system = users table + register + login + logout.
  • Hash passwords with password_hash; check with password_verify.
  • Store login state in a session; check it on every protected page.
  • Use prepared statements for all database queries.
  • Make the email column UNIQUE to prevent duplicates.

Next, understand hashing in depth with password hashing, or manage state with sessions and cookies.

Frequently Asked Questions

What are the main parts of a login system?
Four parts: a users table to store accounts, registration to create an account with a hashed password, login to verify the password and start a session, and logout to end the session. Protecting pages checks the session.
How are passwords stored securely?
Never as plain text. Use password_hash() when registering and password_verify() at login. The database only ever holds the hash, so a leak does not expose real passwords.
How does the site remember a logged-in user?
With a session. After a successful login you set something like $_SESSION["user_id"]. Every protected page checks that this session value exists before showing content.
How do I stop duplicate email registrations?
Make the email column UNIQUE in the database, and check for an existing email before inserting. This prevents two accounts sharing the same email.
Why use prepared statements in login code?
Login and registration handle user input that touches the database. Prepared statements keep that input separate from SQL, preventing SQL injection — a must for any auth code.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicContact Form with Email Your progress: 40 / 50 (80%) · Lesson 41 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free