0

I for some reason can't get my session variables to work after processing a login script (database is linked and working and session_start() has been defined but still won't work).

I've referenced all stuff needed and still won't work, please see code below.

global.php (this gets added to the top of pages such as index):


    error_reporting(E_ALL ^ E_NOTICE);
    
    // Start
    session_start();
    
    define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
    define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
    define('T', 'tpl/');
    define('I', 'interfaces/');
    
    // Management
    require_once C . 'config.php';
    
    // Interfaces
    require_once A . I . 'interface.engine.php';
    require_once A . I . 'interface.core.php';
    require_once A . I . 'interface.template.php';
    require_once A . I . 'interface.users.php';
    
        // TPL
        require_once A . T . I . 'interface.forms.php';
    
    // Classes
    require_once A . 'class.engine.php';
    require_once A . 'class.core.php';
    require_once A . 'class.template.php';
    require_once A . 'class.users.php';
    
        // TPL
        require_once A . T . 'class.forms.php';
    
    // OBJ
    $engine = new Kit\engine();
    $core = new Kit\core($connection); 
    $template = new Kit\template($connection);
    $users = new Kit\users($connection);
    
    $template->Initiate();

index.php (for the form and testing the session user id is showing):


    <?php
    define('IN_INDEX', true);
    include_once(realpath($_SERVER["DOCUMENT_ROOT"]) . '/kit/global.php');
    ?>
    
    <?php if (isset($_SESSION['cerror'])) { echo $_SESSION['cerror']; unset($_SESSION['cerror']); } ?>
    
    <?php echo password_hash("test", PASSWORD_DEFAULT); ?>
    
    <?php echo $users->Me("username"); ?>
    
    <form method="post" action="/kit/app/forms/class.login.php">
    <p><label for="username">Username:</label><br />
                    <input type="email" name="email" id="username" required /></p>
    
                    <p><label for="password">Password:</label><br />
                    <input type="password" name="password" id="password" required /></p>
                        
                    <input type="submit" name="login" class="button round" value="Sign in!" />
    </form>

the login php post submission:


    <?php
    
    namespace Kit;
    
    define('IN_INDEX', true);
    
    require_once(realpath($_SERVER["DOCUMENT_ROOT"] . '/kit/global.php'));
    
        // ----------------------------- Login
    
        if (isset($_POST["login"]))
        {
            $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
            $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
    
            if ($users->emailTaken($email))
            {
                $user_qry = $connection->pdo->prepare("SELECT * FROM `kit_user_accounts` WHERE `email`=?");
                $user_qry->execute([$email]);
                $user_row = $user_qry->fetch();
    
                // Account Lockout
                if ($user_row["login_attempts"] == 0)
                {
                    $core->alert("error", "your account is locked out"); 
                    header('Location: /index'); exit();
                }
    
                // Password Works
                if (password_verify($password, $user_row["password"]))
                {
                    if (password_needs_rehash($user_row["password"], PASSWORD_DEFAULT))
                    {
                        $users->updateUser("password", password_hash($password, PASSWORD_DEFAULT), "email", $email);
                    }
    
                    // Banned?
                    if (!$users->isBanned($user_row["id"]))
                    {
                        // Token Creation
                        $token = bin2hex(random_bytes(32));
                        $users->createToken($token, $user_row["id"], $_SERVER['REMOTE_ADDR'], $core->operatingSystem(), $core->browser(), date("Y-m-d H:i:s", strtotime("+31 days")), $core->timestamp());
                    }
                    else
                    {
                        $core->alert("error", "youre currently banned"); 
                        header('Location: /index'); exit();
                    }
                }
                else
                {
                    // Wrong Password + Additional login attempts update
                    $users->loginAttempts($email);
                    $core->alert("warning", "youve entered the wrong password"); 
                    header('Location: /index'); exit();
                }
            }
            else
            {
                // Email Doesnt Exist
                $core->alert("error", "email doesnt exist"); 
                header('Location: /index'); exit();
            }
        }
    ?>

the class.users.php which processes token creation / cookie creation and finishes the log in:


    <?php
    
    namespace Kit;
    
    if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
    
    class users implements iUsers
    {
     
        public $info = array();
    
        public $connection;
    
        public function __construct($connection)
        {
            $this->connection = $connection;
        }
    
        // ----------------------------- Authenticate
        final public function isLogged()
        {
            if (!isset($_SESSION['user_id']))
            {
                if (isset($_COOKIE['accesstoken']))
                {
                    $token = $_COOKIE['accesstoken'];
    
                    $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_user_tokens` WHERE `token`=?");
                    $qry->execute([$token]);
    
                    if ($qry->rowCount() == 1)
                    {
                        $row = $qry->fetch();
                        if ($row["expiry_date"] > date("Y-m-d H:i:s"))
                        {
                            $_SESSION['user_id'] = $row["user"];
                        }
                    }
                }
            }
        }
    
        final public function Me($info)
        {
            if (isset($_SESSION['user_id']))
            {
                $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_user_accounts` WHERE `id`=?");
                $qry->execute([$_SESSION['user_id']]);
    
                if ($qry->rowCount() == 1)
                {
                    $row = $qry->fetch();
                    return $row["".$info.""];
                }
            }
        }
    
        // ----------------------------- Checks
        final public function emailTaken($email)
        {
            $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_user_accounts` WHERE `email`=?");
            $qry->execute([$email]);
            if ($qry->rowCount() > 0) 
            { 
                return true; 
            }
    
            return false;
        }
    
        final public function isBanned($user)
        {
            $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_bans` WHERE `user`=?");
            $qry->execute([$user]);
            if ($qry->rowCount() > 0) 
            { 
                return true; 
            }
    
            return false;
        }
    
        // ----------------------------- Updating
        final public function updateUser($key, $value, $type, $k)
        {
            $qry = $this->connection->pdo->prepare("UPDATE `kit_user_accounts` SET `".$key."`=? WHERE `".$type."`=?");
            $qry->execute([$value, $k]);
        }
    
        final public function loginAttempts($user)
        {
            $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_user_accounts` WHERE `email`=?");
            $qry->execute([$user]);
            if ($qry->rowCount() > 0) 
            { 
                while($row = $qry->fetch())
                {
                    if ($row["login_attempts"] != 0)
                    {
                        $qry = $this->connection->pdo->prepare("UPDATE `kit_user_accounts` SET `login_attempts`=? WHERE `id`=?");
                        $qry->execute([$row["login_attempts"] - 1, $row["id"]]);
                        return true;
                    }
                    else if ($row["login_attempts"] == 0)
                    {
                        $core->alert("error", "youve locked your account"); 
                        header('Location: /index'); exit();
                    }
                }
            }
    
            return false;
    
        }
    
        final public function createToken($token, $user, $ip, $os, $browser, $expiry_date, $date)
        {
            $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_user_tokens` WHERE `token`=?");
            $qry->execute([$token]);
            while ($qry->rowCount() > 0)
            {
                $token = bin2hex(random_bytes(32));
                $qry = $this->connection->pdo->prepare("SELECT * FROM `kit_user_tokens` WHERE `token`=?");
                $qry->execute([$token]);
            }
    
            $create_token_qry = $this->connection->pdo->prepare("INSERT INTO `kit_user_tokens` (`token`,`user`,`ip`,`os`,`browser`,`expiry_date`,`date`) VALUES (?,?,?,?,?,?,?)");
            if ($create_token_qry->execute([$token, $user, $ip, $os, $browser, $expiry_date, $date]))
            {
                setcookie('accesstoken', $token, time()+(86400 * 31), '/');
                $this->updateUser("login_attempts", "3", "id", $user);
                header('Location: /index'); exit();
            }
            else
            {
                $core->alert("error", "token issue"); 
                header('Location: /index'); exit();
            }
        }
    
    }
    
    ?>

Resact87
  • 3
  • 2
  • The question title `"$_SESSION variables not being picked up"` does not reveal much about any possible errors nor does the question really expand upon that premise. Can you clarify your question as `"but still won't work"` helps neither man nor beast? – Professor Abronsius Sep 16 '22 at 22:52
  • Check your log for "Headers already sent" warnings when calling `session_start()`. If it gets this error it can't send the session cookie and session variables won't work. See https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php for how to fix – Barmar Sep 16 '22 at 23:01
  • Suggest moving `session_start()` to the top of the file, first line. You can get `error_reporting` started after that if you need it. – BugLogic Sep 17 '22 at 20:50

0 Answers0