Created
July 28, 2014 09:08
-
-
Save gicolek/38c853daffac1cf0ea81 to your computer and use it in GitHub Desktop.
DB Session Storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simple Class which overwrites the session storage | |
*/ | |
class Like_Saveit_Session_Handler { | |
/** | |
* Store the db | |
* @var object | |
*/ | |
public $db; | |
/** | |
* Store the session table name | |
* @var string | |
*/ | |
public $session_table; | |
public function __construct() { | |
global $wpdb; | |
$wpdb->show_errors(); | |
$this->db = $wpdb; | |
// use these class session handlers for the session | |
session_set_save_handler( | |
array( $this, 'sessionOpen' ), // | |
array( $this, 'sessionClose' ), // | |
array( $this, 'sessionRead' ), // | |
array( $this, 'sessionWrite' ), // | |
array( $this, 'sessionDestroy' ), // | |
array( $this, 'sessionGC' ) // | |
); | |
} | |
/** | |
* Open Session handler | |
*/ | |
public function sessionOpen($database_name, $table_name) { | |
$this->session_table = $table_name; | |
return true; | |
} | |
/** | |
* Read Session handler | |
*/ | |
public function sessionRead($sess_id) { | |
$result = $this->db->get_row( "SELECT * FROM {$this->session_table} WHERE session_id = '{$sess_id}'", ARRAY_A ); | |
// if there are no results return empty string | |
if ( !$result ) { | |
return ""; | |
} else { | |
return $result['session_variable']; | |
} | |
} | |
/** | |
* Write Session handler | |
*/ | |
public function sessionWrite($sess_id, $val) { | |
$time_stamp = $this->getMicroTime(); | |
$result = $this->db->get_row( "SELECT session_id FROM {$this->session_table} WHERE session_id = '{$sess_id}'", ARRAY_A ); | |
if ( !$result ) { | |
$insert = $this->db->insert( | |
$this->session_table, array( | |
'session_id' => $sess_id, | |
'session_variable' => $val, | |
'last_accessed' => $time_stamp | |
) | |
); | |
} else { | |
$update = $this->db->update( | |
$this->session_table, array( | |
'session_variable' => $val, | |
'last_accessed' => $time_stamp | |
), array( 'session_id' => $sess_id ) | |
); | |
} | |
} | |
public function sessionClose() { | |
return true; | |
} | |
public function sessionDestroy($sess_id) { | |
$delete = $this->db->delete( $this->session_table, array( 'session_id' => $sess_id ) ); | |
return true; | |
} | |
public function sessionGC($max_lifetime) { | |
$current_time = getMicroTime(); | |
$delete_query = "DELETE FROM {$session_table} WHERE last_accessed < ({$current_time} - {$max_lifetime})"; | |
return true; | |
} | |
public function getMicroTime() { | |
$mtime = explode( " ", microtime() ); | |
return ($mtime[0] + $mtime[1]); | |
} | |
} | |
//$sh = new Like_Saveit_Session_Handler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment