create login and logout session in php and database

create login and logout session in php and database

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

Stefan Bogdanescu

Founder & Senior Architect

Fixing Session Persistence in Legacy PHP Login Systems

When a login form submits data but the user is immediately redirected back to the index page without ever seeing the secured content, the root cause is almost always a mismatch between what the script expects and what actually exists in the session. In the code provided, this specific behavior points to a critical variable name inconsistency combined with deprecated database practices.

The most immediate blocker preventing navigation from loginproc.php to securedpage.php is a typo in the session check logic. Inside loginproc.php, the successful authentication block correctly sets the session variable:

$_SESSION['username'] = $_POST['user'];

However, the validation logic inside securedpage.php checks for a different key:

if (!isset($_SESSION['user'])) { // <--- Mismatch
    header('Location: career.php');
}

Because the script looks for $_SESSION['user'] but receives $_SESSION['username'], the condition evaluates to true, redirecting the user to career.php. To fix this, you must ensure the key used in loginproc.php matches exactly what securedpage.php expects. Change securedpage.php to check for $_SESSION['username']:

if (!isset($_SESSION['username'])) { 
    header('Location: index.php'); // Redirect back to login instead of career
}

Beyond this logic error, the provided code relies on the mysql_* extension, which was deprecated in PHP 5.5 and removed entirely in PHP 7.0. Using these functions will cause fatal errors on any modern server environment. You must migrate to mysqli or PDO. Furthermore, the current implementation uses md5($_POST['pass']), which is cryptographically broken. If a hacker obtains your database dump, they can instantly reverse-engineer the password hash.

A secure migration involves switching to Prepared Statements with mysqli to prevent SQL injection and implementing password hashing with password_hash(). Here is how the loginproc.php logic should look in a modern, secure context:

<?php
session_start();

// Modern database credentials (ensure these are stored securely)
$host = 'localhost'; 
$db   = 'database';
$user = 'root';
$pass = '';

$mysqli = new mysqli($host, $user, $pass, $db);

if ($mysqli->connect_error) {
    die('Connect Error: ' . $mysqli->connect_error);
}

// Use prepared statements to sanitize input automatically
$stmt = $mysqli->prepare("SELECT id, password FROM members WHERE username = ?");
$userInput = $_POST['user'] ?? '';
$passInput = $_POST['pass'] ?? '';

// Hash the raw password before comparing it to the stored hash
$hashedInput = password_hash($passInput, PASSWORD_DEFAULT);

$stmt->bind_param("s", $userInput);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    // Verify if the hashed input matches the stored hash in the database
    if (password_verify($passInput, $row['password'])) {
        $_SESSION['username'] = $userInput;
        
        // Regenerate session ID to prevent session fixation attacks
        session_regenerate_id(true); 
        
        header('Location: securedpage.php');
        exit();
    }
}

// If authentication fails
header('Location: index.php');
exit();
?>

Once the user is authenticated and redirected, securedpage.php must verify that the session actually contains the data. The corrected check ensures the user remains on the page if logged in:

<?php
session_start();

// Verify the specific session key exists
if (!isset($_SESSION['username'])) { 
    header('Location: index.php');
    exit();
}

// Display secured content
echo "Welcome, <b>" . htmlspecialchars($_SESSION['username']) . "</b>";
?>

Finally, the logout process in logout.php is mostly correct but can be improved by clearing specific session variables before destroying the entire session. While unset() removes a variable from the array, session_destroy() clears the session data on the server side. The standard flow is to unset necessary variables and then destroy the session:

<?php
session_start();

// Remove the username specifically if you want to keep other session data
unset($_SESSION['username']);

// Optional: Clear all session variables
$_SESSION = [];

// Destroy the session cookie on the client side
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Destroy the session data on the server
session_destroy();

header('Location: index.php');
exit();
?>

Migrating from legacy mysql_* functions to modern standards requires updating both the connection logic and the authentication strategy. The key takeaway is consistency in session variable names and adherence to current security best practices regarding password hashing and prepared statements. For developers looking to abstract these concerns further or build scalable applications, exploring frameworks like Laravel can provide robust built-in solutions for sessions and authentication without handling low-level implementation details.

Our network