#43 - PHP Session Class

Date: 2019-01-12 12:00 - PHP

Session class that manages the session for you. Allows to add 'features' which allow to keep track of the use of your session cookies. This allows to delete the cookie when no longer needed.'

<?php

class Session {
    private static function initSession() {
        if (!isset($_SESSION))
            session_start();
    }

    private static function hasSession() {
        return array_key_exists(session_name(), $_COOKIE) || session_id() != '';
    }

    public static function __callStatic($name, $arguments) {
        $args_count = count($arguments);
        if ($args_count == 0) {
            if (self::hasSession())
                self::initSession();
            return isset($_SESSION[$name]) ? @$_SESSION[$name] : false;
        } else {
            self::initSession();
            if ($args_count == 1)
                return $_SESSION[$name] = $arguments[0];
            else
                return $_SESSION[$name] = $arguments;
        }
    }

    public static function destroy() {
        if (isset($_SESSION)) {
            session_unset();
            session_destroy();
            unset($_SESSION);
        }
        setcookie(session_name(),'',0,'/');
        unset($_COOKIE[session_name()]);
    }

    public static function featureAdd($feature) {
        $features = self::_features();
        if ($features === false)
            $features = [];
        $features = array_merge($features, [$feature]);
        self::_features($features);
    }

    public static function featureRemove($feature) {
        if (!self::hasSession())
            return;
        $features = self::_features();
        if ($features === false) {
            self::destroy();
            return;
        }

        $features = array_filter($features, function($value) use($feature) {
            return $value != $feature;
        });

        if (count($features) === 0)
            self::destroy();
        else
            self::_features($features);
    }

    public static function checkSessionFeatures() {
        if (!self::hasSession())
            return;

        $features = self::_features();
        if ($features === false)
            self::destroy();
    }
}

Previous snippet | Next snippet