将PHP Session存在Postgres数据库后端

jopen 10年前

一个开发环境有多个网站,需要使用不同的session,解决方案很多。不过这次也高大上一把,用数据库存,方便以后扩展。

首先是数据库的部分

--drop table php_session  create unlogged table php_session  (      sess_id varchar(32) primary key,      modify_time timestamp with 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 upsert as (          update php_session          set modify_time = current_timestamp, sess_data = $2          where sess_id = $1          returning 1      )      insert into php_session (sess_id, modify_time, sess_data)      select $1, current_timestamp, $2      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_session  create or replace function del_session(varchar) returns void as $del_session$      delete from php_session where sess_id = $1  $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 '30 days'  $del_session$ language sql;

然后是PHP的部分

<?php    session_set_save_handler(      function ($savePath, $sessionName) {//open          return true;      },      function () {//close          return true;      },      function ($id) {//read          $sql = "select get_session($1)";          $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($1, $2)";          pg_query_params(SESSION_CONN, $sql, array($id, $data));          return true;      },      function ($id) {//destroy          $sql = "select del_session($1)";          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');    ?>

然后只要在session_start之前调用这个就可以了

至于SESSION_CONN,那是我定义的一个常量,表示一个指向session数据库的链接而.

来自:http://my.oschina.net/visualgui823/blog/290074