PHP code example of jeph / mysql-session

1. Go to this page and download the library: Download jeph/mysql-session 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/ */

    

jeph / mysql-session example snippets



// Create a PDO connection
$pdo = new PDO(
    dsn: 'mysql:host=localhost;dbname=myapp;charset=utf8mb4',
    username: 'user',
    password: 'password'
);

// Create the session handler
$session_handler = JEPH\MySQL\Session::create( pdo: $pdo );
if ( $session_handler === false ) {
    die( 'Failed to create session handler' );
}

// Register the handler
session_set_save_handler( session_handler: $session_handler, register_shutdown: true );

// Start the session - use sessions as normal from here
session_start();
$_SESSION['user_id'] = 123;

$session_handler = JEPH\MySQL\Session::create(
    pdo: $pdo,
    table_name: 'sessions',           // Session data table (default: 'sessions')
    lock_table_name: 'session_locks', // Lock table (default: 'session_locks')
    lock_timeout: 10,                 // Seconds to wait for lock (default: 10)
    lock_max_age: 30,                 // Seconds before lock is stale (default: 30)
    lock_retry_interval: 100,         // Milliseconds between retries (default: 100)
    security_code: 'your_secret',     // Secret for fingerprint (default: '')
    lock_to_user_agent: true,         // Bind to User-Agent (default: false)
    lock_to_ip: true,                 // Bind to IP address (default: false)
    read_only: false                  // Read-only mode, no locks/writes (default: false)
);
if ( $session_handler === false ) {
    die( 'Invalid configuration' );
}

$session_handler = JEPH\MySQL\Session::create(
    pdo: $pdo,
    security_code: 'a_random_secret_string_12chars',  // Server-side secret
    lock_to_user_agent: true,                          // Bind to browser
    lock_to_ip: true                                   // Bind to IP address
);

$session_handler = JEPH\MySQL\Session::create(
    pdo: $pdo,
    security_code: 'your_secret',
    lock_to_ip: function(): string {
        // Check trusted proxy headers
        // WARNING: Only trust these headers if you control the proxy!
        foreach ( ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP'] as $header ) {
            if ( isset( $_SERVER[$header] ) && $_SERVER[$header] !== '' ) {
                // X-Forwarded-For may contain multiple IPs; take the first
                $ip = explode( ',', $_SERVER[$header] )[0];
                return trim( $ip );
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? '';
    }
);

$session_handler = JEPH\MySQL\Session::create( pdo: $pdo );
session_set_save_handler( session_handler: $session_handler, register_shutdown: true );
session_start();

// For long operations, periodically refresh the lock
foreach ( $large_dataset as $item ) {
    process_item( $item );
    
    // Refresh lock every iteration (or based on time elapsed)
    $session_handler->refresh_lock();
}

session_write_close();

$session_handler = JEPH\MySQL\Session::create(
    pdo: $pdo,
    read_only: true
);
session_set_save_handler( session_handler: $session_handler, register_shutdown: true );
session_start();

// Read session data as normal
$user_id = $_SESSION['user_id'] ?? null;

// Any modifications to $_SESSION will NOT be saved
$_SESSION['last_seen'] = time(); // This change is discarded

if ( $session_handler->is_read_only() ) {
    // Don't try to save important data
    log_warning( 'Attempted to modify session in read-only mode' );
}

// API endpoint that just needs to verify the user is logged in
$session_handler = JEPH\MySQL\Session::create( pdo: $pdo, read_only: true );
session_set_save_handler( session_handler: $session_handler, register_shutdown: true );
session_start();

if ( empty( $_SESSION['user_id'] ) ) {
    http_response_code( 401 );
    exit( json_encode( ['error' => 'Unauthorized'] ) );
}

// Process the API request...

// Homepage that shows different content for logged-in users
$session_handler = JEPH\MySQL\Session::create( pdo: $pdo, read_only: true );
session_set_save_handler( session_handler: $session_handler, register_shutdown: true );
session_start();

$is_logged_in = ! empty( $_SESSION['user_id'] );
// Render page with appropriate content...
sql
CREATE DATABASE jeph_session_test;
CREATE USER 'jeph_session_test'@'localhost' IDENTIFIED BY 'jeph_session_test';
GRANT ALL PRIVILEGES ON jeph_session_test.* TO 'jeph_session_test'@'localhost';
FLUSH PRIVILEGES;