Discuz! Detailed description of SESSION mechanism instances in X

Source: Internet
Author: User
This article mainly introduces Discuz! SESSION mechanism in X, detailed analysis of Discuz in the form of instances! The SESSION mechanism principles and database operation skills in X are of reference value. if you need them, refer to the example in this article to describe Discuz! X. Share it with you for your reference. The details are as follows:

In Discuz! As always in X, the SESSION does not use the SESSION mechanism that comes with PHP, but is a set of built-in mechanisms of the system.

There are two SESSION tables in the database:
One is pre_common_adminsession, which is the SESSION table for the administrator to log on to the background;
The other is the pre_common_session table, which is the SESSION table when all users browse the page at the front-end.
Both tables are memory tables (the read/write speed of memory tables is much higher than that of MYISAM tables and text files ).

In Discuz! In X, SESSION and COOKIE are inseparable because SESSION is the COOKIE read from the client,
Then, relevant function execution is triggered when the page is viewed, and then written to the database SESSION table.

I will take the logon process as an example to explain how the program is executed.
On the front-end homepage, click "log on". a logon window is displayed. fill in the data and submit it. The URL of form submission is:

The code is as follows:

Http://ux.com/member.php? Mod = logging & action = login & loginsubmit = yes & floatlogin = yes & inajax = 1


Commit data is submitted to the member. php file. you can see the following code in the program:

$ Mod =! In_array ($ discuz-> var ['mod'], $ modarray )? 'Logging': $ discuz-> var ['mod']; // The value of mod is the define ('curmodule', $ mod) of the php page to be loaded next ); $ modcachelist = array ('register '=> array ('modreasons', 'stamptypeid', 'fields _ required', 'fields _ optional', 'ipctrl ')); $ cachelist = array (); if (isset ($ modcachelist [CURMODULE]) {$ cachelist = $ modcachelist [CURMODULE];} $ discuz-> cachelist = $ cachelist; $ discuz-> init (); runhooks (); require DISCUZ_ROOT. '. /source/module/member _'. $ mod. '. php'; // complete the inclusion operation of the program

Open the source/module/member/member_logging.php file, which is a class. you can see the following three codes before the class:

$ Ctl_obj = new logging_ctl (); $ method = 'on _'. $ _ G ['GP _ action']; // $ _ G ['GP _ action'] equals to the value of action, that is, login $ ctl_obj-> $ method (); // $ ctl_obj-> on_login ();

The login method can be found in the class. in the method, about 56 rows have the following judgment statement:

If (! Submitcheck ('loginsubmit ', 1, $ seccodecheck) {// when a visitor browses a submitcheck statement, the return value of the submitcheck function is false. The return value is the inverse value and the return value is true. // When a user logs on, the program goes through the else section. the following five codes are displayed :} else {$ _ G ['uid'] = $ _ G ['member'] ['uid'] = 0; $ _ G ['username'] = $ _ G ['member'] ['username'] = $ _ G ['member'] ['password'] = ''; // variable value $ result = userlogin ($ _ G ['GP _ username'], $ _ G ['GP _ password'], $ _ G ['GP _ questionid '], $ _ G ['GP _ answer'], $ _ G ['setting'] ['autoidselect']? 'Auto': $ _ G ['GP _ loginfield ']); // query user data from the database, and return the corresponding information if ($ result ['status']> 0) {// The status value is greater than 0, indicating that this user exists, you can log on to setloginstatus ($ result ['member'], $ _ G ['GP _ cookietime']? 2592000: 0); // Set the logon status, that is, the COOKIE write operation. The data in the COOKIE is the corresponding data in the SESSION, but this function is not responsible for the SESSION write operation.

Let's take a look at the setloginstatus function in source/function/function_login.php, which is a common COOKIE writing operation and will not be explained in detail:

Function setloginstatus ($ member, $ cookietime) {global $ _ G; $ _ G ['uid'] = $ member ['uid']; $ _ G ['username'] = $ member ['username']; $ _ G ['adminid'] = $ member ['adminid']; $ _ G ['groupid'] = $ member ['groupid']; $ _ G ['formhash'] = formhash (); $ _ G ['session'] ['invisable'] = getuserprofile ('invisable'); $ _ G ['member'] = $ member; $ _ G ['core']-> session-> isnew = 1; dsetcookie ('auth ', authcode ("{$ member ['password']} \ t {$ member ['uid']}", 'encoding'), $ cookietime, 1, true ); // authcode-encrypted dsetcookie ('loginuser'); dsetcookie ('activationauth'); dsetcookie ('pmnum ');}

This can be said that most of the login process has been completed, but when the COOKIE is not cleared, it will always exist on the client. if the timeout occurs, the program will judge to discard the COOKIE and write it again.

Next let's take a look at the SESSION operation class in DZX, in the source/class/calss_core.php file:
The SESSION will be loaded in each request in the program. this is executed by the _ init_session method in the discuz_core core class. this method is placed in the init method of the class, indicating that the class is loaded each time, the SESSION is automatically written.

Function _ init_session () {$ this-> session = new discuz_session (); // Create a SESSION class if ($ this-> init_session) {// read data from the COOKIE $ this-> session-> init ($ this-> var ['cooker'] ['Sid '], $ this-> var ['clientip'], $ this-> var ['uid']); $ this-> var ['Sid '] = $ this-> session-> sid; $ this-> var ['session'] = $ this-> session-> var; // Determine whether the SID is equal or not. it indicates that multiple users log on to the website on the same host and need to re-write the COOKIE if ($ this-> var ['Sid ']! = $ This-> var ['cookies'] ['Sid']) {dsetcookie ('Sid', $ this-> var ['Sid'], 86400 );} if ($ this-> session-> isnew) {if (ipbanned ($ this-> var ['clientip']) {$ this-> session-> set ('groupid', 6) ;}} if ($ this-> session-> get ('groupid') = 6) {$ this-> var ['member'] ['groupid'] = 6; sysmessage ('User _ banned');} // The UID is not empty, in addition, the SESSION or SESSION needs to be updated and times out to change the user status, you need to log on again if ($ this-> var ['uid'] & ($ this-> session-> isnew | ($ this-> session-> get (' lastactive ') + 600) <TIMESTAMP) {$ this-> session-> set ('lastactivity', TIMESTAMP ); $ update = array ('lastip' => $ this-> var ['clientip'], 'lastactive' => TIMESTAMP); if ($ this-> session-> isnew) {$ update ['lastvisit'] = TIMESTAMP;} DB: update ('Common _ member_status ', $ update, "uid = '". $ this-> var ['uid']. "'");}}}

The SESSION operation class is discuz_session. let's look at the two methods in this class:

// This function is responsible for generating new sessions, but is not responsible for writing data to the database function create ($ ip, $ uid) {// creates a SESSION and inserts data, A random number of six digits is generated by the random function, that is, the unique time of the session is the current time, and the sid is the sid $ this-> isnew = true in the cookie; $ this-> var = $ this-> newguest; $ this-> set ('Sid ', random (6); $ this-> set ('uid ', $ uid); $ this-> set ('IP', $ ip); $ this-> set ('lastactivity', time ()); $ this-> sid = $ this-> var ['Sid ']; return $ this-> var;} // this function updates the SESSION function update () {if ($ this-> sid! = Null) {$ data = daddslashes ($ this-> var); if ($ this-> isnew) {$ this-> delete (); DB :: insert ('Common _ session', $ data, false, false, true);} else {DB: update ('Common _ session', $ data, "sid = '$ data [sid]'");} dsetcookie ('Sid ', $ this-> sid, 86400 );}}

So far, we know the specific function used to insert a SESSION into the database and the connection with the COOKIE, but we still don't know how to trigger this operation.
Open the source/function/function_core.php file, find the function, updatesession, which updates the SESSION:

function updatesession($force = false) {  global $_G;  static $updated = false;  if(!$updated) {   $discuz = & discuz_core::instance();   foreach($discuz->session->var as $k => $v) {    if(isset($_G['member'][$k]) && $k != 'lastactivity') {     $discuz->session->set($k, $_G['member'][$k]);    }   }   foreach($_G['action'] as $k => $v) {    $discuz->session->set($k, $v);   }   $discuz->session->update();   $updated = true;  }  return $updated; }

Search for this function in the program source code. the following code is found in many templates:

The code is as follows:

{Eval updatesession ();}


This function is triggered when you browse the page and the SESSION is written to the database.

Sort out your thoughts:

Step 1: When a user logs on, the program writes cookies to the client. These cookies are part of the SESSION data, such as SID, IP, and TIME. They do not contain key information such as the user name and password.

Step 2: After successful login, the program will automatically refresh the page, send a request to the server again, load the discuz_core core class on the server, and read the SESSION information from the COOKIE, but it has not been written into the database.

Step 3: After the core class is loaded, the program continues to execute. Finally, the template is loaded and the updatesession function is triggered. The SESSION is written to the database.

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.