java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

php session session_set_save_handler 机制

php自身带功能,将session的数据从之前的files 改变到其他任何地方。比如mysql redis等等,方便你分布式的集群应用。
看一下原理

  
Can't connect to $SESS_DBHOST as $SESS_DBUSER";   
        echo "
  • MySQL Error: " . mysql_error(); die; } if (! mysql_select_db($SESS_DBNAME, $SESS_DBH)) { echo "
  • Unable to select database $SESS_DBNAME"; die; } return true; } function sess_close() { return true; } function sess_read($key) { global $SESS_DBH, $SESS_LIFE; $qry = "SELECT value FROM session_tbl WHERE sesskey = '$key' AND expiry > " . time(); $qid = mysql_query($qry, $SESS_DBH); if (list($value) = mysql_fetch_row($qid)) { return $value; } return false; } function sess_write($key, $val) { global $SESS_DBH, $SESS_LIFE; $expiry = time() + $SESS_LIFE; //过期时间 $value = addslashes($val); $qry = "INSERT INTO session_tbl VALUES ('$key', $expiry, '$value')"; $qid = mysql_query($qry, $SESS_DBH); if (! $qid) { $qry = "UPDATE session_tbl SET expiry = $expiry, value = '$value' WHERE sesskey = '$key' AND expiry > " . time(); $qid = mysql_query($qry, $SESS_DBH); } return $qid; } function sess_destroy($key) { global $SESS_DBH; $qry = "DELETE FROM session_tbl WHERE sesskey = '$key'"; $qid = mysql_query($qry, $SESS_DBH); return $qid; } function sess_gc($maxlifetime) { global $SESS_DBH; $qry = "DELETE FROM session_tbl WHERE expiry < " . time(); $qid = mysql_query($qry, $SESS_DBH); return mysql_affected_rows($SESS_DBH); } session_set_save_handler( "sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc"); session_start(); ?>
  • 使用方法:
    在使用session前
    将之前的session_start()
    改成

     require_once("session.class.php");
    CREATE TABLE IF NOT EXISTS `session_tbl` (
      `sesskey` varchar(255) NOT NULL,
      `expiry` varchar(255) NOT NULL,
      `value` varchar(255) NOT NULL,
      UNIQUE KEY `sesskey_2` (`sesskey`),
      KEY `sesskey` (`sesskey`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;


    This entry was posted in PHP and tagged , , . Bookmark the permalink.
    月小升QQ 2651044202, 技术交流QQ群 178491360
    首发地址:月小升博客https://java-er.com/blog/php-session-session_set_save_handler/
    无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
    您的评论是我写作的动力.

    Leave a Reply