How To Create a Basic Login System with PHP and MySQL

Build a functional and secure login form using PHP and MySQL in under 30 minutes.

2 min read โ€ข
187 1 0

Build a secure login system in under 30 minutes using PHP and MySQL , perfect for beginners learning authentication.

๐Ÿ” Why Build a Login System?

Most dynamic websites require a secure way to authenticate users. This tutorial shows you how to build a functional login system using PHP and MySQL without a framework. You'll learn how to safely verify credentials and manage sessions.

๐Ÿ“ฆ Step 1: Create the MySQL Database

CREATE DATABASE login_demo; USE login_demo; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL );

Insert a test user with hashed password:

INSERT INTO users (username, password) VALUES ('admin', '$2y$10$EXAMPLE.HASHED.PASSWORD');

You can use password_hash('yourpassword', PASSWORD_DEFAULT) in PHP to generate a secure hash.

๐Ÿงพ Step 2: Create the Login Form (HTML)

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

โš™๏ธ Step 3: login.php (Authentication Logic)

<?php session_start(); require 'db.php'; // your PDO connection file if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = trim($_POST['username']); $password = $_POST['password']; $stmt = $pdo->prepare('SELECT * FROM users WHERE username = ?'); $stmt->execute([$username]); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password'])) { $_SESSION['user'] = $user['username']; header('Location: dashboard.php'); exit; } else { echo 'Invalid credentials'; } } ?>

๐Ÿง‘โ€๐Ÿ’ป Step 4: Create dashboard.php

<?php session_start(); if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; } ?> <h1>Welcome, <?= htmlspecialchars($_SESSION['user']) ?></h1> <a href="logout.php">Logout</a>

๐Ÿšช Step 5: Create logout.php

<?php session_start(); session_destroy(); header('Location: login.php'); exit; ?>

๐Ÿ›ก๏ธ Security Tips

  • Always hash passwords using password_hash()
  • Use https in production to encrypt login data
  • Escape all output with htmlspecialchars()
  • Use prepared statements to prevent SQL injection
  • Regenerate session IDs upon login

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Replying to someone. Cancel