Session management Wrapper-Klasse
Session management wrapper class
The session management is designed to be a singleton, which keeps a reference to the own
instance reference in a static class variable. A good reason to have a wrapper for the normal
PHP session management is that you can easily re-implement this class and make it loading the
session from memory cache or a MySql memory table. Use the static functions to start or stop
the session, and the instance()
function to access the created instance. Example:
Die Session-Management-Klasse ist als Singleton-Objekt, welches eine Referenz auf die
eigene Instanz in einer statischen Klassenvariable hält, designed. Das macht nicht nur Sinn
für Autolisting in Entwicklungsumgebungen, sondern ermöglichst es auch die Klasse neu zu
implementieren und statt des normalen Session-Handlings in PHP auf MemCache oder RAM Tabellen
in MySql zuzugreifen. Mit den statischen Funktionen kann die Session gestartet oder
geschlossen werden, mit der Funktion instance()
kann auf das Objekt zugegriffen werden.
Beispiel:
Sample source code
Anwendungsbeispiel
<?php
require_once 'swlib/swlib.class.php';
use sw\Session;
// Start the session
Session::start();
$rand = rand(1, 10);
if ($rand == 1) {
// Regenerate session ID
Session::instance()->regrnerateId();
} else if ($rand == 2) {
// Destroy the session
Session::instance()->destroy();
}
print "<html><body><pre>";
// Work with a session variable
$_SESSION['test'] = !isset($_SESSION['test']) ? 0 : $_SESSION['test'] + 1;
// Print some data
print "Counter = " . $_SESSION['test'] . "\n";
print "Session id = " . Session::instance()->id() . "\n";
print "Session name = " . Session::instance()->getName() . "\n";
print "Session expires = " . Session::instance()->getCacheExpireTime() . "\n";
// This function is more for anaysis purposes
print "Session save path = " . Session::instance()->getSavePath() . "\n";
// Conditionally stop the session
if ($Condition_that_requires_closing_the_session) {
Session::stop();
} else {
// The session will be written when the object is destructed,
// this is when the script has finished and PHP unsets all
// variables.
}
if ($rand == 1) {
print "\n(Session id regenerated)\n";
} else if ($rand == 2) {
print "\n(Session destroyed)\n";
}
print "</pre></body></html>";
?>
Class source code
Klassen-Quelltext
<?php
/**
* Session management wrapper. This class can be used to replace the PHP standard
* session handling. Principally this class does nothing differemt, but the class
* can be easily replaced with a database-based session handling or the like.
* @gpackage de.atwillys.sw.php.swLib
* @author Stefan Wilhelm
* @copyright Stefan Wilhelm, 2005-2010
* @license GPL
* @version 1.0
*/
namespace sw;
class Session {
/**
* The one any only session object
* @staticvar session
*/
private static $instance = null;
/**
* Session startup, autimatically creates session instance.
* @param string $name=null
* @return Session
*/
public static final function start($name=null) {
if (is_null(self::$instance)) {
self::$instance = new self($name);
}
return self::$instance;
}
/**
* Closes the session, writes the session file
*/
public static final function stop() {
self::$instance = null;
}
/**
* Returns the Session singleton instance
* @return Session
*/
public static final function instance() {
return self::$instance;
}
/**
* Session instance constructor.
* Starts new session.
* @param string $name=null
* @return Session
*/
private final function __construct($name=null) {
$name = trim($name);
if (!empty($name)) {
if (!is_numeric($name) && !is_alnum($name)) {
@session_name($name);
} else {
throw new LException('Session name is invalid: :name', array(':name' => $name));
}
}
@session_start();
}
/**
* Session instance destructor.
*/
public final function __destruct() {
@session_write_close();
}
/**
* Session stop with cockie, vars and cache.
* @return void
*/
public final function destroy() {
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
@setcookie(session_name(), '', time() - 42000, '/');
}
@session_unset();
@session_destroy();
}
/**
* Returns session IDs
* @return string
*/
public final function id() {
return @session_id();
}
/**
* Generates a new session ID, keeps session data
*/
public final function regrnerateId() {
if (!@session_regenerate_id()) {
throw new LException("ID regeneration failed.");
}
}
/**
* Returns the session name
* @return string
*/
public final function getName() {
return @session_name();
}
/**
* Returns the save path for session variables
* @return string
*/
public final function getSavePath() {
return @session_save_path();
}
/**
* Returns the session cache expire time in
* minutes.
* @return int
*/
public final function getCacheExpireTime() {
return @session_cache_expire();
}
/**
* Returns an associative array with all saved and not garbaged sessions,
* where the keys are the session ids and the values are the last file
* modification time.
* @return array
*/
public static final function getActiveSessions() {
$sessions = array();
foreach (glob(session_save_path() . "sess_*") as $key => $file) {
$f = pathinfo($file);
$f = str_replace('sess_', '', $f['filename']);
$sessions[$f] = filemtime($file);
}
return $sessions;
}
/**
* Returns the IP address of the client browser
* @return string
*/
public static final function getClientIpAddress() {
if (isset($_SERVER["REMOTE_ADDR"]))
return $_SERVER["REMOTE_ADDR"];
if (isset($_SERVER["HTTP_CLIENT_IP"]))
return $_SERVER["HTTP_CLIENT_IP"];
if (@getenv("HTTP_CLIENT_IP"))
return @getenv("HTTP_CLIENT_IP");
if (getenv("HTTP_X_FORWARDED_FOR"))
return @getenv("HTTP_X_FORWARDED_FOR");
if (@getenv("REMOTE_ADDR"))
return @getenv("REMOTE_ADDR");
return null;
}
/**
*
*/
public static final function getClientUserAgent() {
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
foreach (array(
'/chrome/i' => 'chrome', // chrome contains the text "safari"
'/safari/i' => 'safari',
'/firefox/i' => 'firefox',
'/msie/i' => 'internet-explorer',
'/opera/i' => 'opera',
) as $key => $value) {
if (preg_match($key, $agent)) {
return $value;
}
}
return null;
}
}