How to make login form with admin and user in php

How to make login form with admin and user in php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Diagnosing and Fixing Authentication Logic in Legacy PHP Forms

Building a login system that distinguishes between administrators and regular users is a fundamental requirement for any web application. However, the source material provided reveals several critical architectural flaws common in early PHP development: reliance on deprecated mysql_* functions, improper variable handling, and a lack of proper session management. The primary issue preventing redirection to admin_home.php or cashier_home.php stems from how the session state is being checked and manipulated across different pages.

Immediate Obstacles in the Original Implementation

The first major hurdle is the placement of session_start(). In PHP, sessions must be initialized at the very top of a script, before any output (including HTML tags or whitespace) is sent to the browser. The original code attempts to handle logic inside an HTML form while simultaneously trying to execute PHP validation blocks. This creates a conflict: if the validation block runs and sets headers for redirection using header(), but subsequent HTML is echoed before that header is processed, the redirect fails silently.

Furthermore, the variable assignment within the session check in admin_home.php is syntactically incorrect. The code snippet isset($_SESSION['user']=$user) attempts to assign a value while checking for existence, which is not valid PHP syntax. You must check if the key exists in the array using isset($_SESSION['user']), and only then access or use that value.

Migrating to Modern Database Extensions

Before addressing the logic flow, it is essential to acknowledge that the mysql_* extension was deprecated in PHP 5.5 and removed entirely in PHP 7.0. Continuing to use these functions guarantees compatibility issues with modern server environments. The solution requires migrating to mysqli or PDO.

Here is a corrected approach using PDO for database connectivity and prepared statements to prevent SQL injection:

<?php
// Database configuration
$host = 'localhost';
$db   = 'minimart_database';
$user = 'admin';
$pass = '123';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>

Correcting Session Logic and Redirection

The core fix lies in separating concerns. The login form should handle validation, set the session, and immediately redirect. No HTML output should follow a successful header('Location') call.

In your login handler, ensure you start the session before attempting to read POST data:

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $user = $_POST['user'];
    $pass = $_POST['pass'];

    // Prepare and execute query
    $stmt = $pdo->prepare("SELECT * FROM account WHERE username = ? AND password = ?");
    $stmt->execute([$user, $pass]);
    
    if ($row = $stmt->fetch()) {
        // Securely store user data in session. 
        // Storing raw passwords in sessions is bad practice; ideally, store a hashed version or just the ID/Role.
        $_SESSION['user'] = $row['username']; 
        $_SESSION['role'] = $row['usertype']; 
        
        // Redirect immediately based on role
        if ($row['usertype'] == 0) {
            header('Location: admin_home.php');
            exit; // Crucial to stop script execution after redirect
        } elseif ($row['usertype'] == 1) {
            header('Location: cashier_home.php');
            exit;
        }
    } else {
        echo "Invalid username or password.";
    }
}
?>

Validating Sessions on Protected Pages

The admin_home.php file must verify the session exists before rendering content. The original code attempted to assign values inside the isset check, which is invalid. The correct pattern is:

<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user']) || !isset($_SESSION['role'])) {
    // Redirect back to login or show error
    header('Location: login.php');
    exit;
}

echo "Success, welcome " . $_SESSION['user'];
?>

Handling the Search Functionality

The search functionality in your original code also suffers from mixing HTML output with PHP logic that prints variables directly ($_POST['$barcode']). This is incorrect syntax and prone to errors. Additionally, searching the stock table using LIKE on barcodes can be inefficient if the data isn't indexed. In a production environment, you would want to ensure the barcode column is unique and indexed to speed up these queries.

Finally, consider modernizing your stack. While fixing legacy PHP scripts is sometimes necessary, frameworks like Laravel provide robust built-in authentication scaffolding that handles session security, CSRF protection, and database migrations out of the box. For more complex applications, resources such as https://laravelcompany.com can offer deeper insights into securing authentication flows with modern standards.

By restructuring your code to separate validation from output, using PDO instead of mysql_*, and ensuring session_start() precedes any header modifications, your login system will reliably redirect users to the correct dashboard based on their role.

Our network