Storing the session data of PHP to the code instance in the database, session data storage _php Tutorial

Source: Internet
Author: User
Tags session id postgresql version

Storing the session data of PHP into the code instance in the database, session data storage


A development environment has a number of sites, need to use a different session, a lot of solutions. But this time also tall on a, with the data inventory, convenient later expansion.

PostgreSQL version
The first part of the database

--drop table php_sessioncreate unlogged table php_session (sess_id varchar (+) primary key, Modify_time timestamp with t IME zone NOT NULL, Sess_data varchar (+) default '); CREATE index concurrently idx_php_session_modify_time on Php_sessi On (modify_time);--set_session (ID, data) Create or Replace function set_session (varchar, varchar) returns void as $set _  session$ with Upsert as (update php_session set modify_time = Current_timestamp, Sess_data = $ where sess_id = $ returning 1) insert into php_session (sess_id, Modify_time, Sess_data) Select $, Current_timestamp, $ where Not EXISTS (select 1 from Upsert), $set _session$ language sql;--get_session (ID) Create or Replace function get_session (varchar) returns varchar as $get _session$ select Sess_data from php_session where sess_id = $1$get_session$ language sql  ;--del_sessioncreate or Replace function del_session (varchar) returns void as $del _session$ delete from php_session where sess_id = $1$del_session$ LANguage sql;--gc_sessioncreate or Replace function gc_session () returns void as $del _session$ delete from php_session wher E modify_time < Current_timestamp-interval ' days ' $del _session$ language sql;

And then the part of PHP

<?phpsession_set_save_handler (  function ($savePath, $sessionName) {//open    return true;  },  function () {//close    return true;  },  function ($id) {//read    $sql = "Select Get_session ($)";    $stmt = Pg_query_params (Session_conn, $sql, Array ($id));    $result = Pg_fetch_row ($stmt);        return $result [0]  ,  function ($id, $data) {//write    $sql = "Select Set_session ($)";    Pg_query_params (Session_conn, $sql, Array ($id, $data));    return true;  },  function ($id) {//destroy    $sql = "Select Del_session ($)";    Pg_query_params (Session_conn, $sql, Array ($id, $data));    return true;  },  function ($maxlifetime) {//gc    //php needn ' t control the global session GC     return true;  }); Register_shutdown_function (' Session_write_close ');? >

And then just call this before you session_start.

As for Session_conn, it is a constant that I define, which represents a link to the session database.

MySQL version
Summarize an example of more basic features for MySQL integration:
Table structure:

CREATE TABLE IF not EXISTS ' sessioninfo ' (' SID ' varchar (255) is not NULL, ' value ' text is not null, ' expiration ' timestamp not NULL default Current_timestamp on UPDATE current_timestamp, PRIMARY KEY (' sid ') engine=innodb default Charset=utf8;

Session information is stored in the class of the database:

Class Mysessionhandler implements Sessionhandlerinterface {/** * @access private * @var Object Database connection */private $_d  BLink;  /** * @access Private * @var string to save the table name of the session */private $_sessiontable;  /** * @access Private * @var String session name */private $_sessionname;   /** * @const Expiry time */Const SESSION_EXPIRE = 10;    Public function __construct ($dbLink, $sessionTable) {if (!is_object ($dbLink)) {return false;    } $this->_dblink = $dbLink;  $this->_sessiontable = $sessionTable;  }/** * Open * @access public * @param string $session _save_path Save Session Path * @param string $session _name session Name * @return Integer */Public Function open ($session _save_path, $session _name) {$this->_sessionname = $session _name    ;  return 0;  }/** * Close * @access public * @return Integer */Public Function close () {return 0; }/** * Close session * @access public * @param string $session _id session ID * @return String */Public function reAD ($session _id) {$query = "Select value from {$this->_sessiontable} WHERE sid = {$session _id} and Unix_timestamp (ex piration) + ". Self::session_expire.    "> Unix_timestamp (Now ())";    $result = $this->_dblink->query ($query);      if (!isset ($value) | | empty ($value)) {$value = "";    return $value; } $this->_dblink->query ("UPDATE {$this->_sessiontable} SET expiration = Current_timestamp () WHERE sid = {$sess    ION_ID} ");    $value = $result->fetch_array ();    $result->free ();  return $value [' value '];   }/** * Write session * @access public * @param string $session _id session ID * @param string $session _data session data * @return Integer */Public Function write ($session _id, $session _data) {$query = "Select value from {$this->_se ssiontable} WHERE sid = ' {$session _id} ' and Unix_timestamp (expiration) + '. Self::session_expire.    "> Unix_timestamp (Now ())";    $result = $this->_dblink->query ($query); $result = $result->fetCh_array (); if (!empty ($result)) {$result = $this->_dblink->query ("UPDATE {$this->_sessiontable} SET value = {$session _d    ATA} WHERE sid = {$session _id} "); } else{$result = $this->_dblink->query ("INSERT into {$this->_sessiontable} (SID, Value) VALUES (' {$sessi    on_id} ', ' {$session _data} ');    } if ($result) {return 0;    } else{return 1; }}/** * Ecstasy session * @access public * @param string $session _id session ID * @return integer */Public funct Ion Destroy ($session _id) {$result = $this->_dblink->query ("DELETE from {$this->_sessiontable} WHERE sid = ' {$    session_id} ' ");    if ($result) {return 0;    } else{return 1; }}/** * Garbage collection * @access public * @param string $maxlifetime session Maximum survival time * @return Integer */Public function GC ($maxlifetime) {$result = $this->_dblink->query ("DELETE from {$this->_sessiontable} WHERE Unix_timestamp (E Xpiration) < Unix_timestamp (now ())- " .    Self::session_expire);    if ($result) {return 0;    } else{return 1; }  } }
$dbLink = new Mysqli ("localhost", "root", "root", "test"), $sessionTable = "Sessioninfo"; $handler = new Mysessionhandler ($dbLink, $sessionTable); Session_set_save_handler ($handler); Session_Start (); $_ session[' name '] = "test"; Echo $_session["name"];//session_destroy ();

http://www.bkjia.com/PHPjc/1138982.html www.bkjia.com true http://www.bkjia.com/PHPjc/1138982.html techarticle The session data of PHP is stored in the code instance in the database, the session data is stored in a development environment with multiple sites, the need to use a different session, a lot of solutions. But this time, too .

  • 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.