Use MySQL memory table to replace PHP session class _php Skill

Source: Internet
Author: User
Tags key string php session set time sql error
Copy Code code as follows:

<?php
/**
@Usage: Use some storage (MySQL or memcache) instead of PHP Sessoin
@author: Lein
@Version: 1.0
*/
Session_Start ();
if (!isset ($_session[' test ')) {
$_session[' test ']= "123_lein_". Date ("y-m-d h:i:s");
}

Class session{

Session data
Private $data;
Engine,mysql or Memcache
Private $engine;
PHP Session expire Time
Private $sessionexpiredTime;
Current user ' s session cookie value
Private $sessionID;

Public Function session ($engineBase =null, $engineName = ' mysql ', $storage _name= ' php_session ') {
try{
$this->sessionexpiredtime = intval (Ini_get ("Session.cache_expire")) *60;
}catch (Exception $Exception) {
$this->sessionexpiredtime = 1200;
}
@session_start ();
$this->sessionid=session_id ();
$className = $engineName. " Sessionengine ";
$this->engine = new $className (
Array
' Storage_name ' => $storage _name,//mysql table name or MEMCAHCE key which stores data;
' Expire_time ' => $this->sessionexpiredtime,
' Data_too_long_instead_value ' => ' {__data is *$* to long__} '
),
$this->sessionid,
& $engineBase
);
$this->init ();
$this->engine->refresh ();
$this->engine->cleanup ();
}
Private Function init ()
{
$this->data = $this->engine->get ();
if (Emptyempty ($this->data) &&!emptyempty ($_session)) {
$this->data = $_session;
$this->engine->create (False, $this->data);
}
else if (Emptyempty ($this->data))
{
$this->engine->create (False, $this->data);
}
}
Private Function __get ($NM)
{
if (Isset ($this->data[$nm])) {
$r = $this->data[$nm];
return $r;
}
Else
{
return NULL;
}
}
Private Function __set ($NM, $val)
{
$this->data[$nm] = $val;
$this->engine->set (False, $this->data);
}
function __destruct () {
$this->data = NULL;
$this->engine->close ();
$this->engine = NULL;
}
}

Interface Sessionengine
{
/*
* Set Varibles
* @param $arr Array,array (varible name=>varible value,...)
*/
Public Function setvariable ($arr);
/*
* Get Session value
* @param $key string
*/
Public function Get ($key = "");
/*
* Set Session value
* @param $key string
* @param $value string
*/
Public function set ($key = "", $value = "");
/*
* Set Session value
* @param $key string
* @param $value string
*/
Public Function Create ($key = "", $value = "");
/*
* Update the session ' s invalid time
* @param $key string
*/
Public Function Refresh ($key = "");
/*
* Close MySQL or memcache connection
*/
Public function close ();
/*
* Delete Expired Sessions
*/
Public function Cleanup ();
}

Final class Mysqlsessionengine implements sessionengine{
Private $id = "";
Private $storage _name= ' php_session ';
Private $storage _name_slow= ' Php_session_slow ';
Private $data _too_long_instead_value = ' {__data is ~ to long__} ';//if the data is longer than $max _session_data_length and are using MySQL 4 or below,insert this value into Memery table instead.
Private $expire _time=1200;
Private $max _session_data_length = 2048;
Private $conn;
Private $mysql _version;
Public Function Mysqlsessionengine ($arr =array (), $key = "", &$_conn) {
$this->setvariable ($arr);
$this->id = $key;
if (Emptyempty ($this->id) | | strlen ($this->id)!=32) {
throw new Exception (__file__.) -> ". __line__.": Session ' s cookie name can ' t be empty and it must have just ');
}
$this->conn = $_conn;
if (! $this->conn| |! Is_resource ($this->conn)) {
throw new Exception (__file__.) -> "__line__.": Need a MySQL connection! ");
}
$this->mysql_version = $this->getone ("Select Floor (Version ())");
if ($this->mysql_version<5) {
$this->max_session_data_length = 255;
}
}
Public Function SetVariable ($arr) {
if (!emptyempty ($arr) &&is_array ($arr)) {
foreach ($arr as $k => $v) {
$this-> $k = $v;
if ($k = = ' Storage_name ') {
$this->storage_name_slow = $v. ' _slow ';
}
}
}
}
Public function Get ($key = "") {
if ($key = = "") $key = $this->id;
$return = $this->getone (' Select value from '. $this->storage_name. ' Where id= '. $key. ');
if ($return = = $this->data_too_long_instead_value)
{
$return = $this->getone (' Select value from '. $this->storage_name_slow. ' Where id= '. $key. ');
}
if (! $return)
{
$mysqlError = mysql_error ($this->conn);
if (Strpos ($mysqlError, "doesn ' t exist")!==false)
{
$this->inittable ();
}
$return = Array ();
}
Else
{
$return = Unserialize ($return);
}
return $return;
}
Public function Close () {
@mysql_close ($this->conn);
}
Public Function Cleanup () {
if ($this->mysql_version>4) {
$sql = ' Delete from '. $this->storage_name. ' While Date_add (Time,interval '. $this->expire_time. ') SECOND) <current_timestamp () ';
}else{
$sql = ' Delete from ', $this->storage_name. ' While time+ '. $this->expire_time. ' <unix_timestamp () ';
}
$this->execute ($sql);
}
Public Function Refresh ($key = "") {
if ($this->mysql_version>4) {
$sql = ' Update '. $this->storage_name. ' Set Time=current_timestamp () where id= "'. $key. '"
}else{
$sql = ' Update '. $this->storage_name. ' Set Time=unix_timestamp () where id= "'. $key. '"
}
$return = $this->execute ($sql);
if (! $return) {
$this->inittable ();
$return = $this->execute ($sql, true);
}
return $return;
}
Public Function Create ($key = "", $value = "") {
if ($key = = "") $key = $this->id;
if ($value!= "") $value = mysql_real_escape_string (serialize ($value), $this->conn);
if (strlen ($value) > $this->max_session_data_length) throw new Exception (__file__. " -> ". __line__.": Session data is long than max allow Length (". $this->max_session_data_length."));
if ($this->mysql_version>4) {
$sql = ' replace into '. $this->storage_name. ' Set value=\ '. $value. ' \ ', id= '. $key. ', Time=current_timestamp () ';
}else{
$sql = ' replace into '. $this->storage_name. ' Set value=\ '. $value. ' \ ', id= '. $key. ', Time=unix_timestamp () ';
}
$return = $this->execute ($sql);
if (! $return) {
$this->inittable ();
$return = $this->execute ($sql, true);
}
return $return;
}
Public function set ($key = "", $value = "") {
if ($key = = "") $key = $this->id;
if ($value!= "") $value = mysql_real_escape_string (serialize ($value), $this->conn);
$sql = ' Update '. $this->storage_name. ' Set value=\ '. $value. ' \ ' where id= '. $key. ' ";
if (strlen ($value) > $this->max_session_data_length)
{
if ($this->mysql_version>4) {
throw new Exception (__file__.) -> ". __line__.": Session data is long than max allow Length (". $this->max_session_data_length."));
}
$sql = ' replace into '. $this->storage_name_slow. ' Set value=\ '. $value. ' \ ', id= '. $key. ', Time=unix_timestamp () ';
$this->execute ($sql, true);
$sql = ' Update '. $this->storage_name. ' Set value=\ '. $this->data_too_long_instead_value. ' \ ' where id= '. $key. ' ";
}
$return = $this->execute ($sql);
if (! $return) {
$this->inittable ();
$return = $this->execute ($sql, true);
}
return $return;
}
Private Function inittable () {
if ($this->mysql_version>4) {
$sql = "
CREATE TABLE if not exists ' ". $this->storage_name." ` (
' id ' char ' not NULL default ' ERR ',
' Value ' VARBINARY (". $this->max_session_data_length.") Null
' Time ' timestamp not NULL default current_timestamp on Update Current_timestamp,
PRIMARY KEY (' id '),
KEY ' time ' (' time ')
) Engine=memory;
";
}else{
$sqlSlow = "
CREATE TABLE if not exists ' ". $this->storage_name." _slow ' (
' id ' char ' not NULL default ' ERR ',
' Value ' text NULL,
' Time ' int (a) NOT null default ' 0 ',
PRIMARY KEY (' id '),
KEY ' time ' (' time ')
) Engine=myisam;
";
$this->execute ($sqlSlow, true);

$sql = "
CREATE TABLE if not exists ' ". $this->storage_name." ` (
' id ' char ' not NULL default ' ERR ',
' Value ' VARCHAR (255) NULL,
' Time ' int (a) NOT null default ' 0 ',
PRIMARY KEY (' id '),
KEY ' time ' (' time ')
) Engine=memory;
";
}
return $this->execute ($sql, true);
}
Private function Execute ($sql, $die =false)
{
if ($die)
{
mysql_query ($sql, $this->conn) or Die ("EXE SQL Error:<br>". Mysql_error (). " <br> ". $sql." }
Else
{
mysql_query ($sql, $this->conn);

if (Mysql_error ()) {
return false;
}else{
return true;
}
}
}
Private Function GetOne ($sql, $die =false) {
$rs = $this->query ($sql, $die);
if ($rs && ($one = mysql_fetch_row ($rs)) {
return $one [0];
}else{
return false;
}
}
Private function Query ($sql, $die =false) {
if ($die)
$rs = mysql_query ($sql, $this->conn) or Die ("Query SQL Error:<br>". Mysql_error (). " <br> ". $sql." Else
$rs = mysql_query ($sql, $this->conn);
return $rs;
}
}

$lnk = mysql_connect (' localhost ', ' root ', ' 123456 ')
Or Die (' Not connected: '. mysql_error ());

Make Foo the current db
mysql_select_db (' Test ', $lnk) or Die (' can\ ' t use foo: '. mysql_error ());
$S = new session ($LNK);
if (! $S->last) {
$S->last = time ();
}
echo "Visit at". $S->last. " <br> ";
if (! $S->lastv) {
$S->lastv = 0;
}
$S->lastv++;
echo "lastv=". $S->lastv. " <br> ";
echo "test=". $S->test. " <br> ";
if (Isset ($_get[' Max ')) {
$S->boom = str_repeat ("OK", 255);
}
if (isset ($_get[' boom ')) {
$S->boom = $_get[' boom '];
}
echo "boom=". $S->boom. " <br> ";
?>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.