Created
February 9, 2012 03:16
-
-
Save javierwilson/1776966 to your computer and use it in GitHub Desktop.
php session management using postgresql
This file contains 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 | |
# | |
# manejador de sesiones | |
# | |
$sessiondb = pg_pconnect('dbname=sessions user=bob password=secret'); | |
function on_session_start($save_path, $session_name) { | |
error_log("on_session_start: " . $session_name . " ". session_id()); | |
} | |
function on_session_end() { | |
global $sessiondb; | |
pg_close($sessiondb); | |
} | |
function on_session_read($key) { | |
global $sessiondb; | |
#error_log("on_session_read: " . $key); | |
$stmt = "SELECT session_data FROM sessions WHERE session_id ='$key' AND CURRENT_TIMESTAMP < session_expiration"; | |
$sth = pg_query($sessiondb, $stmt); | |
if($sth) { | |
$row = pg_fetch_array($sth); | |
return($row['session_data']); | |
} else { | |
return $sth; | |
} | |
} | |
function on_session_write($key, $val) { | |
global $sessiondb; | |
#error_log("on_session_write $key = $val"); | |
$val = pg_escape_string($val); | |
$result = pg_query($sessiondb, "SELECT session_id FROM sessions WHERE session_id='$key'"); | |
$existe = pg_num_rows($result); | |
if ($existe === 1) | |
$sql = "UPDATE sessions SET session_data ='$val', session_expiration = CURRENT_TIMESTAMP + interval '1 hour' WHERE session_id ='$key'"; | |
else | |
$sql = "INSERT INTO sessions VALUES ('$key', '$val',CURRENT_TIMESTAMP + interval '1 hour')"; | |
pg_query($sessiondb, $sql); | |
} | |
function on_session_destroy($key) { | |
global $sessiondb; | |
pg_query($sessiondb, "DELETE FROM sessions WHERE session_id = '$key'"); | |
} | |
function on_session_gc($max_lifetime) { | |
global $sessiondb; | |
pg_query($sessiondb, "DELETE FROM sessions WHERE session_expiration > CURRENT_TIMESTAMP"); | |
} | |
# Set the save handlers | |
session_set_save_handler("on_session_start", "on_session_end", "on_session_read", "on_session_write", "on_session_destroy", "on_session_gc"); | |
session_start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment