PHP uses MySQL to save session sessions, mysqlsession_php tutorial

Source: Internet
Author: User
Tags garbage cleaner

PHP uses MySQL to save session sessions, Mysqlsession


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

In a lot of large systems generally have this function, but to separate out the analysis, online reliable information is not too much here I collated an article issued 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.

//////use the MySQL save session first to 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 (& $this, ' 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->db_ SERVER, $this->db_user, $this->db_pass)) {echo "sorry! MYSQL Error:cA ' 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,//session  Expiration time = Last Update time + Session maximum usage $SessionArray = addslashes ($VArray); $Query = "INSERT into sessions (Sessionkey,sessionexptime,sessionarray) VALUES ('". $SessionKey. "', '". $SessionExpTime. "'  , ' ". $SessionArray." ') "; $Result = mysql_query ($Query, $thisDB_SELECT_DB); if (! $Result) {$Query = "UPDATE sessions SET sessionexptime = '". $SessionExpTime. "', Sessionarray = '". $SessionArray. " ' 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 of the original use of Session_Start, replace with $session = new mysqlsession ()///NOTE: To open the database before the main program exits, the database cannot be closed before the program quits, or an error will occur.

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

http://www.bkjia.com/PHPjc/1019079.html www.bkjia.com true http://www.bkjia.com/PHPjc/1019079.html techarticle PHP uses MySQL to save session sessions, Mysqlsession This example describes how PHP uses MySQL to save session sessions. Share to everyone for your reference. The specific analysis is as follows: in ...

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