0
0
PhpHow-ToBeginner · 4 min read

How to Create a Login System in PHP: Simple Step-by-Step Guide

To create a login system in PHP, you need to collect user credentials via a form, verify them against stored data (usually in a database), and use sessions to keep the user logged in. Use password_hash() to store passwords securely and password_verify() to check them during login.
📐

Syntax

A basic PHP login system involves these parts:

  • Form: HTML form to get username and password.
  • Processing: PHP script to check credentials.
  • Sessions: To remember logged-in users.
  • Password handling: Use password_hash() to store and password_verify() to check passwords securely.
php
<?php
// Start session to track user login
session_start();

// Example: Check login credentials
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Normally, get user data from database
    $stored_hash = '$2y$10$examplehashedpasswordstringhere'; // hashed password

    if ($username === 'user' && password_verify($password, $stored_hash)) {
        $_SESSION['username'] = $username; // Save login state
        echo 'Login successful';
    } else {
        echo 'Invalid username or password';
    }
}
?>
💻

Example

This example shows a simple login form and PHP script that checks username and password, then starts a session if login is correct.

php
<?php
session_start();

// Hardcoded user data for demo
$users = [
    'alice' => '$2y$10$wHq7Q9xQ0vQ1YzZxQ1YzZeFq6vQ1YzZxQ1YzZeFq6vQ1YzZxQ1YzZe', // password: secret123
];

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (isset($users[$username]) && password_verify($password, $users[$username])) {
        $_SESSION['username'] = $username;
        $message = 'Login successful! Welcome, ' . htmlspecialchars($username) . '.';
    } else {
        $message = 'Invalid username or password.';
    }
}

if (isset($_SESSION['username'])) {
    echo '<p>You are logged in as ' . htmlspecialchars($_SESSION['username']) . '.</p>';
    echo '<form method="post" action="logout.php"><button type="submit">Logout</button></form>';
} else {
    echo '<form method="post">
        <label>Username: <input type="text" name="username" required></label><br>
        <label>Password: <input type="password" name="password" required></label><br>
        <button type="submit">Login</button>
    </form>';
    echo '<p>' . $message . '</p>';
}
?>
Output
<p>You are logged in as alice.</p><form method="post" action="logout.php"><button type="submit">Logout</button></form>
⚠️

Common Pitfalls

Common mistakes when creating a PHP login system include:

  • Storing passwords as plain text instead of using password_hash().
  • Not starting sessions with session_start() before using session variables.
  • Not validating or sanitizing user input, which can lead to security issues.
  • Not checking the request method before processing login data.
  • Failing to protect pages by checking if the user is logged in.
php
<?php
// Wrong: Storing plain password
$stored_password = 'mypassword';

// Right: Store hashed password
$stored_hash = password_hash('mypassword', PASSWORD_DEFAULT);

// Wrong: Using session without session_start()
// $_SESSION['user'] = 'alice'; // This will not work

// Right:
session_start();
$_SESSION['user'] = 'alice';
?>
📊

Quick Reference

Remember these key functions and steps:

  • session_start(): Begin session to track user login.
  • password_hash(): Create a secure password hash.
  • password_verify(): Check password against hash.
  • Use $_POST to get form data.
  • Always validate and sanitize inputs.
  • Protect pages by checking if user is logged in with session.

Key Takeaways

Always hash passwords with password_hash() before storing them.
Use session_start() to manage user login sessions.
Verify passwords securely with password_verify() during login.
Validate and sanitize all user inputs to avoid security risks.
Protect restricted pages by checking if the user is logged in.