A code instance that stores PHP session data in a database _php instance

Source: Internet
Author: User

A development environment has multiple sites that need to use different sessions and many solutions. But this time also tall on a, with data inventory, easy to expand later.

PostgreSQL Edition
first, the part of the database.

--drop table php_session Create unlogged table php_session (sess_id varchar () primary key, Modify_time timestamp W

ITH time zone not NULL, Sess_data varchar (3000) default ");

CREATE index concurrently idx_php_session_modify_time on php_session (modify_time); --set_session (ID, data) Create or Replace function set_session (varchar, varchar) returns void as $set _session$ with Upse RT as (update php_session set modify_time = Current_timestamp, Sess_data = $ where sess_id = $ returnin G 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 = $ $get _session$ language SQL; --del_session Create or Replace function del_session (varchar) returns void as $del _session$ Delete from Php_session WHere sess_id = $ $del _session$ language SQL; --gc_session Create or Replace function gc_session () returns void as $del _session$ delete from php_session where modify_

 Time < Current_timestamp-interval ' days ' $del _session$ language sql;

And then there's the PHP part.

<?php

Session_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 just call this before the Session_Start, okay?

As for Session_conn, that's a constant I've defined that represents a link to the session database.

MySQL version
summarize an example of more basic functionality for MySQL integration:
Table structure:

 CREATE TABLE IF not EXISTS ' sessioninfo ' (
 ' sid ' varchar (255) NOT NULL,
 ' value ' text not NULL,
 ' expiration ' Ti Mestamp not NULL DEFAULT current_timestamp on UPDATE current_timestamp,
 PRIMARY KEY (' Sid ')
 Engine=innodb Defau LT Charset=utf8;

Session information is stored in the class of the database:

Class Mysessionhandler implements Sessionhandlerinterface {/** * @access private * @var Object Database Connection * * * PRIV
  Ate $_dblink;
  /** * @access Private * @var string Save the Session table name * * Private $_sessiontable;
  /** * @access Private * @var String Session name * * Private $_sessionname;
 
  /** * @const Expiration 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 the path to save session @param string $session _name sess Ion name * @return Integer */Public Function open ($session _save_path, $session _name) {$this->_sessionname = $se
    Ssion_name;
  return 0;
  /** * @access public * @return Integer/Public Function closed () {return 0; /** * Close Session * @access public * @param string $session _ID Session ID * @return string/Public function read ($session _id) {$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);
      if (!isset ($value) | | | empty ($value)) {$value = "";
    return $value; $this->_dblink->query ("UPDATE {$this->_sessiontable} SET expiration = Current_timestamp () WHERE sid = {$ses
    SION_ID} ");
    $value = $result->fetch_array ();
    $result->free ();
  return $value [' value ']; /** * Write Session * @access public * @param string $session _id session ID * @param string $session _data Sessio n Data * @return integer/Public Function write ($session _id, $session _data) {$query = ' select value from {$th is->_sessiontable} 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 _
    Data} WHERE sid = {$session _id} "); else{$result = $this->_dblink->query (INSERT into {$this->_sessiontable} (SID, Value) VALUES (' {$ses
    sion_id} ', ' {$session _data} ');
    } if ($result) {return 0;
    } else{return 1; }/** * Ecstasy session * @access public * @param string $session _id session ID * @return integer/Pub  Lic function 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 The maximum lifetime of Session * @return Integer/Public Function GC ($maxlifetime) {$result = $this; _dblink->query ("DELETE from {$this->_sessiontable} WHERE unix_timestamp (expiration) < 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 ();

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.