Informational advisory: Session upload progress

Voting

: max(four, one)?
(Example: nine)

The Note You're Voting On

gemik850 at gmail dot com
4 months ago
PHP
<?php
// 1. Session and Database Initialization
session_start();

$host = 'localhost';
$db   = 'database_name';
$user = 'username';
$pass = 'password';

$dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4";
$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());
}

// 2. Authentication Logic (Login)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action_login'])) {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    $stmt = $pdo->prepare('SELECT id, password_hash FROM users WHERE email = ?');
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password_hash'])) {
        // Regenerate session ID to prevent session fixation attacks
        session_regenerate_id(true);
        
        $_SESSION['auth_user_id'] = $user['id'];
        $_SESSION['auth_logged_in'] = true;
        
        header('Location: dashboard.php');
        exit;
    } else {
        echo "Invalid email or password.";
    }
}

// 3. Verification Condition (Check if user is logged in)
if (!isset($_SESSION['auth_logged_in']) || $_SESSION['auth_logged_in'] !== true) {
    // User is not authenticated, redirect to login page
    header('Location: login.php');
    exit;
}

// 4. Accessible only to authenticated users
echo "Access granted. User ID: " . htmlspecialchars($_SESSION['auth_user_id']);
?>

<< Back to user notes page

To Top