Php uses MySQL to save session

Source: Internet
Author: User
This article mainly introduces how php uses MySQL to save session sessions. it involves php session operations and database related skills, for more information about how to use MySQL to save session, see the example in this article. Share it with you for your reference. The specific analysis is as follows:

This function is generally available in many large systems. However, if you want to separate the analysis and there is not much information on the Internet, I have compiled an article to share it with you.

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

1) for distributed systems, files can only be stored on one machine.
2) for systems with high traffic volumes, when files are used, each session is saved in a file, and the directory is too large, it is difficult to find the session file.

To save a session using MySQL, you must first create a 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 "the 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 'Session' ('sessionkey' varchar (32) NOT NULL default '', 'sessionarray' blob not null, 'sessionexptime' int (20) unsigned not null default '0', primary key ('sessionkey'), KEY 'sessionkey' ('sessionkey ')) ENGINE = MyISAM default charset = utf8 "; // create a database SQL statement mysql_query ($ SQL); echo" the database table is created successfully! ";?>

The MysqlSession class is as follows:

<? Php class MysqlSession {// note that there is a page for using Session. The page must be the top level and cannot be left blank at the beginning of the page. Private $ DB_SERVER = "localhost"; // database server host name private $ DB_NAME = ""; // database name private $ DB_USER = "root "; // MYSQL database access username: private $ DB_PASS = ""; // MYSQL database access password: private $ DB_SELECT_DB = ""; // private $ SESS_LIFE = 1440; // maximum Session duration, in seconds. Private $ SESS_LIFE = 0; function MysqlSession (& $ sessionDB) {// session_write_close (); $ this-> DB_NAME = & $ sessionDB; $ this-> SESS_LIFE = get_cmd_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 the database connection if (! $ This-> DB_SELECT_DB = mysql_pconnect ($ this-> DB_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 (); // do not read after expiration. $ 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 the Session expiration time, session expiration time = last update time + maximum Session usage time $ SessionArray = addslashes ($ VArray); $ Query = "insert into SessionKey, SessionExpTime, SessionArray) VALUES ('". $ SessionKey. "','". $ SessionExpTime. "','". $ SessionArray. "')"; $ Result = mysql_query ($ Query, $ this-> DB_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) {// system call of this garbage collector. It is cleared once every 1440 seconds by default. // You can set the parameters 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: replace session_start with $ session = new MysqlSession ()

Note: you must open the database before the program is included. you cannot close the database before the main program Exits. Otherwise, an error occurs.

I hope this article will help you with php programming.

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.