PHP code example of initphp / sessions

1. Go to this page and download the library: Download initphp/sessions library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

initphp / sessions example snippets


use InitPHP\Sessions\Session;

Session::createImmutable()
    ->start();
    

Session::set('username', 'admin')
        ->set('mail', '[email protected]');
/**
 * OR
 * 
 * $_SESSION['username'] = 'admin';
 * $_SESSION['mail'] = '[email protected]';
 */

echo Session::get('username', 'Undefined');
/**
 * OR
 * 
 * echo $_SESSION['username'] ?? 'Undefined';
 */

use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\RedisAdapter;

$adapter = new RedisAdapter([
    'host'      => '127.0.0.1', // string
    'port'      => 6379, // int
    'timeout'   => 0, // int
    'password'  => null, // null or string
    'database'  => 0,
    'ttl'       => 86400,
    'prefix'    => 'sess'
]);

Session::createImmutable($adapter)
    ->start();

use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\PDOAdapter;

$pdo = new \PDO('mysql:host=localhost;dbname=test', 'root', '');

$adapter = new PDOAdapter(['pdo' => $pdo, 'table' => 'app_sessions']);

Session::createImmutable($adapter)
    ->start();

use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\MemCacheAdapter;

$adapter = new MemCacheAdapter([
        'host'          => '127.0.0.1', // string
        'port'          => 11211, // int
        'weight'        => 1, // int
        'raw'           => false, // boolean
        'prefix'        => null, // null or string
        'ttl'           => 86400, // int
]);

Session::createImmutable($adapter)
    ->start();

use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\CookieAdapter;

$adapter = new CookieAdapter(['name' => 'sessDataCookieName', 'key' => 'topSecretAppKey', 'ttl' => 86400]);

Session::createImmutable($adapter)
    ->start();

use InitPHP\Sessions\Session;
use InitPHP\Sessions\Adapters\MongoDBAdapter;

$adapter = new MongoDBAdapter(['dsn' => 'mongodb://127.0.0.1:27017', 'collation' => 'sessDbName.sessCollectionName']);

Session::createImmutable($adapter)
    ->start();