How to Create a Secure PHP MySQL Login Script Using Sessions

Last updated on June 24th, 2025 at 09:57 am

If you’re building a website with user accounts, having a secure login system is essential. In this step-by-step guide, you’ll learn how to create a PHP login system using MySQL and sessions — the right way. We’ll use prepared statements, password hashing, and session handling to ensure everything is secure and up to modern standards.

Let’s get started!

What You’ll Learn

  • How to connect PHP with MySQL securely
  • How to store and verify passwords using password_hash()
  • How to use sessions to keep users logged in
  • Best practices to protect your login system from common threats

Step 1: Set Up the Database

Start by creating a users table in your MySQL database:

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

Make sure to store hashed passwords, not plain text.


Step 2: Create the Database Connection File (config.php)

This file will be used to connect to your MySQL database securely:

<?php
$mysqli = new mysqli("localhost", "your_username", "your_password", "your_database");

if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
?>

Keep this file out of the public web root and never expose credentials.


Step 3: Build the Login Form (login.php)

<form method="post" action="authenticate.php">
<label>Username:</label>
<input type="text" name="username" required>

<label>Password:</label>
<input type="password" name="password" required>

<input type="submit" value="Login">
</form>

You can style this form with CSS later for a better UI.


Step 4: Authenticate Users Securely (authenticate.php)

Now the real security happens. Here’s a safe way to handle login with PHP sessions and hashed passwords.

<?php
session_start();
require 'config.php';

$username = trim($_POST['username']);
$password = $_POST['password'];

// Use a prepared statement to avoid SQL injection
$stmt = $mysqli->prepare("SELECT id, password FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $hashed_password);
$stmt->fetch();

if (password_verify($password, $hashed_password)) {
session_regenerate_id(true); // Prevent session fixation
$_SESSION['user_id'] = $id;
$_SESSION['username'] = $username;
header("Location: welcome.php");
exit;
}
}
echo "Invalid username or password.";
?>

Security Tips:

  • Never store plain passwords.
  • Always use password_hash() and password_verify().

Step 5: Create a Protected Page (welcome.php)

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
echo "Welcome, " . htmlspecialchars($_SESSION['username']) . "!";
?>

Only logged-in users can see this page.


Step 6: Logout (logout.php)

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

This securely ends the user session.


Security Best Practices for Your Login System

Here are a few extra tips to make your PHP login even more secure:

  • Always use HTTPS (SSL certificate)
  • Sanitize user inputs using htmlspecialchars() and trim()
  • Limit login attempts to prevent brute-force attacks
  • Use CSRF tokens in your login form
  • Validate both username and password server-side

11 Comments

  1. xhaaejdqjy

    a good one..

  2. gfsfcvknwln

    Good a very simple script for loging in using php….nice

  3. tvnpmsm

    very simple login script i have ever seen..

  4. fuowhrywnwh

    gud one

  5. Esod

    Work very fine and it’s was so easy to use !

    Thank’s a lot !!!

  6. umair

    this login script is very helpful for new visitor must see this code

  7. n

    gud one!
    TQ

  8. saravana

    it’s really awesome. i have never seen before…

    Thanks for easy script

  9. whaa...

    whaaaaaaaaaaa………….

  10. Areen

    your a Genius….. Thnks to made us life easier…..

  11. Full Container Load

    First and easy script.