1<?PHP2 classSession3 {4 Private Static $handle=NULL;5 Private Static $ip=NULL;6 Private Static $lifetime=NULL;7 Private Static $time=NULL;8 9 Static functionInit$pdo)Ten { OneSelf::$handle=$pdo; ASelf::$ip= !Empty($_server["REMOTE_ADDR"]) ?$_server["REMOTE_ADDR"]: "Unknow"; -Self::$lifetime=Ini_get(' Session.gc_maxlifetime '); -Self::$time= Time(); the } - - Static functionStart$pdo) - { +Self::init ($pdo); - Session_set_save_handler( + Array(__class__, ' open '), A Array(__class__, ' close '), at Array(__class__, ' read '), - Array(__class__, ' write '), - Array(__class__, ' Destroy '), - Array(__class__, ' GC ') - ); - Session_Start(); in } - to Public Static functionOpen$path,$name) + { - return true; the } * $ Public Static functionClose ()Panax Notoginseng { - return true; the } + A Public Static functionRead$PHPSESSID) the { + $sql= "SELECT * from session where PHPSESSID =?"; - $smit= Self::$handle->prepare ($sql); $ $smit->execute (Array($PHPSESSID)); $ - if(!$result=$smit->fetch (PDO::Fetch_assoc)) - { the return‘‘; - }Wuyi the if(Self::$ip!=$result[' Client_ip ']) - { WuSelf::d Estroy ($PHPSESSID); - return‘‘; About } $ - if( ($result[' update_time '] + self::$lifetime) < self::$time) - { -Self::d Estroy ($PHPSESSID); A return‘‘; + } the - return $result[' Data ']; $ } the the Public Static functionWrite$PHPSESSID,$data) the { the $sql= "SELECT * from session where PHPSESSID =?"; - $stmt= Self::$handle->prepare ($sql); in $stmt->execute (Array($PHPSESSID)); the the if($result=$stmt->fetch (PDO::Fetch_assoc)) About { the if($result[' data ']! =$data|| Self::$time-30 >$result[' Update_time ']) the { the $sql= "Update session set Update_time =?, data =?" where PHPSESSID =? "; + $stmt= Self::$handle->prepare ($sql); - $stmt->execute (Array(Self::$time,$data,$PHPSESSID)); the }Bayi the the}Else - { - if(!Empty($data)) the { the $sql= "INSERT into session (PHPSESSID, Update_time, CLIENT_IP, data) VALUES (?,?,?,?)"; the $sth= Self::$handle->prepare ($sql); the $sth->execute (Array($PHPSESSID, Self::$time, Self::$ip,$data)); - } the } the return true; the }94 the Public Static functionDestroy$PHPSESSID) the { the $sql= "Delete from session where PHPSESSID =?";98 $sth= Self::$handle->prepare ($sql); About $sth->execute (Array($PHPSESSID)); - return true;101 }102 103 Public Static functiongc$lifetime)104 { the $sql= "Delete from session where Update_time <?";106 $stmt=self::$handler->prepare ($sql);107 $stmt->execute (Array(Self::$time-self::$lifetime));108 return true;109 } the }111 the Try{113 $pdo=NewPDO ("Mysql:host=localhost;dbname=test", "Root", "" "); the}Catch(pdoexception$e) the { the Echo $e-getMessage ();117 }118 119Session::start ($pdo);
Session writes to Database