Skip to content

Instantly share code, notes, and snippets.

@EionRobb
Created August 7, 2021 01:39
Show Gist options
  • Save EionRobb/c8d2e95f25353e10d2d688ce4669f5c7 to your computer and use it in GitHub Desktop.
Save EionRobb/c8d2e95f25353e10d2d688ce4669f5c7 to your computer and use it in GitHub Desktop.
PHP session handler for couchbase 7
<?php
// auto_prepend_file = /path/to/couchbase-php-session-handler.php
class CouchbaseSessionHandler implements SessionHandlerInterface {
/**
* The prefix to be used in Couchbase keynames.
*/
protected $_keyPrefix = 'session:';
/**
* Define a expiration time of 10 minutes.
*/
protected $_expire = 600;
protected $_connection = null;
protected $_collection = null;
/**
* Set the default configuration params on init.
*/
public function __construct($host, $bucket, $username, $password) {
$options = new \Couchbase\ClusterOptions();
$options->credentials($username, $password);
$this->_connection = new \Couchbase\Cluster($host, $options);
$bucket = $this->_connection->bucket($bucket);
$bucket->setTranscoder('\Couchbase\passThruEncoder', '\Couchbase\passThruDecoder');
$this->_collection = $bucket->defaultCollection();
}
/**
* Open the connection to Couchbase (called by PHP on `session_start()`)
*/
public function open($savePath, $sessionName) {
return true;
}
/**
* Close the connection. Called by PHP when the script ends.
*/
public function close() {
return true;
}
/**
* Read data from the session.
*/
public function read($sessionId) {
$key = $this->_keyPrefix . $sessionId;
try {
$res = $this->_collection->getAndTouch($key, $this->_expire);
$result = $res->content();
} catch (Couchbase\DocumentNotFoundException $e) {
return '';
}
return (string) $result;
}
/**
* Write data to the session.
*/
public function write($sessionId, $sessionData) {
$key = $this->_keyPrefix . $sessionId;
$opts = new \Couchbase\UpsertOptions();
$opts->expiry($this->_expire);
$result = $this->_collection->upsert($key, $sessionData, $opts);
return $result ? true : false;
}
/**
* Delete data from the session.
*/
public function destroy($sessionId) {
$key = $this->_keyPrefix . $sessionId;
try {
$result = $this->_collection->remove($key);
} catch (\Couchbase\DocumentNotFoundException $e) {
$result = true;
}
return $result ? true : false;
}
/**
* Run the garbage collection.
*/
public function gc($maxLifetime) {
return true;
}
}
$handler = new CouchbaseSessionHandler('couchbase://127.0.0.1?sasl_mech_force=PLAIN', 'sessions', 'Admin', 'password');
session_set_save_handler($handler, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment