Save session with MySQL

Source: Internet
Author: User
Tags garbage cleaner php class php programming

This article is from: http://www.lai18.com/content/433951.html

This example describes how PHP uses MySQL to save session sessions. Share to everyone for your reference. The specific analysis is as follows:

in many large systems generally have this function, but to separate out the analysis, the online information is not too much here I collated an article sent to share with you

using MySQL to save session sessions has many advantages over files:

1) for distributed systems, files can only be saved on a single machine

2) for large-scale system, the use of files when each session is saved in a file, the directory will be super large, find session files will be more difficult.

to save a session using MySQL, you first create the session table:

<?php$hostname_login = "localhost";//Server address$ Username_login = "root"; User name $password _login = ""; password//$data _name = "session"; Database Name$login = mysql_pconnect ($hostname _login, $username _login, $password _login) or Trigger_error (mysql_ Error (), e_user_error); $sql = "SHOW DATABASES like '". $data _name. "'"; If it is Existif ($rs _table=mysql_query ($sql, $login)) {if ($rs _value=mysql_fetch_array ($rs _table)) {echo "Database already exists!   \n! ";   Exit ();   }} $sql = "CREATE DATABASE $data _name"; mysql_query ($sql); Crate Databaseecho "Database created successfully! \ n "; mysql_select_db ($data _name, $login); $sql = "CREATE TABLE ' Sessions ' (' sessionkey ' varchar) not NULL default ' ', ' Sessio NArray ' blob not null, ' sessionexptime ' int (a) unsigned NOT null default ' 0 ', PRIMARY key (' SessionKey '), key ' SessionKey ' (' SessionKey ')) Engine=myisam DEFAULT Charset=utf8 "; New Database SQL statement mysql_query ($sql); echo "Successfully created a new database table! ";? 

The Mysqlsession class is as follows:

<?php class Mysqlsession {//Note in the page with session.  The page must be shelf and the page cannot be left blank at the beginning. Private $DB _server = "localhost"; Database server host name private $DB _name = ""; Database name private $DB _user = "root"; MYSQL database access User name private $DB _pass = "";   MYSQL database access password private $DB _select_db = ""; Private $SESS _life = 1440;  The maximum length of time to use the session, in seconds.  Private $SESS _life = 0;    Function mysqlsession (& $sessionDB) {//session_write_close ();    $this->db_name = & $sessionDB;        $this->sess_life = Get_cfg_var ("Session.gc_maxlifetime");    Session_module_name (' user '); Session_set_save_handler (Array (& $this, ' Sess_open '), Array (& $this, ' Sess_close '), Array (& $t  His, ' Sess_read '), Array (& $this, ' Sess_write '), Array (& $this, ' Sess_destroy '), Array (& $this,    ' sess_gc '));  Session_Start (); } function Sess_open ($save _path, $session _name) {//Open database connection if (! $this->db_select_db = mysql_pconnect ($this-&gt ;D B_server, $this->db_usER, $this->db_pass)) {echo "sorry!       MYSQL Error:can ' t connect to $this->db_server as $DB _user ";       echo "MySQL Error:", mysql_error ();     Die } if (! mysql_select_db ($this->db_name, $this->db_select_db)) {echo ' sorry!       MYSQL error:unable to select database $this->db_name ";     Die   } return true;   } function Sess_close () {return true; } function Sess_read ($SessionKey) {$Query = "Select Sessionarray from sessions WHERE SessionKey = '". $SessionKey. "' and Sessionexptime >".    Time ();    Expires without reading.     $Result = mysql_query ($Query, $this->db_select_db);     if (list ($SessionArray) = Mysql_fetch_row ($Result)) {return $SessionArray;   } return false;        } function Sess_write ($SessionKey, $VArray) {$SessionExpTime = time () + $this->sess_life;     Update session expiration time, session expiration = Last Update time + Session maximum usage $SessionArray = addslashes ($VArray); $Query = "INSERT into sessions(Sessionkey,sessionexptime,sessionarray)     VALUES (' ". $SessionKey." ', ' ". $SessionExpTime." ', ' ". $SessionArray." ') ";       $Result = mysql_query ($Query, $this->db_select_db); if (! $Result) {$Query = "UPDATE sessions SET sessionexptime = '". $SessionExpTime. "', Sessionarray = '". $SessionA Rray. "' WHERE SessionKey = ' ". $SessionKey." ' and Sessionexptime >. "       Time ();     $Result = mysql_query ($Query, $this->db_select_db);   } return $Result;     } function Sess_destroy ($SessionKey) {$Query = "DELETE from sessions WHERE SessionKey = '". $SessionKey. "'";       $Result = mysql_query ($Query, $this->db_select_db);   return $Result; } function sess_gc ($maxlifetime) {//This garbage cleaner system is called.    The default is 1440 seconds to clear once.    Parameters can be set in php.ini. $Query = "DELETE from sessions WHERE Sessionexptime <".     Time ();     $Result = mysql_query ($Query, $this->db_select_db);   Return Mysql_affected_rows ($this->db_select_db); }}?>



usage: In place where the original session_start is used, replace with $session = new Mysqlsession ()

Note: To open the database before the main program exits, the database cannot be closed before the program is included, or an error will occur.

I hope this article is helpful to everyone's PHP programming

Save session with MySQL

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.