discuz! Example of session mechanism in X _php instance

Source: Internet
Author: User
The examples in this paper describe discuz! The session mechanism in X. Share to everyone for your reference. Specific as follows:

In discuz! X in as always, the session does not use PHP's own session mechanism, but the system of a set of self-contained mechanism.

You can see two SESSION tables in the database:
One is pre_common_adminsession, is the administrator log in the background of the SESSION table;
The other is the Pre_common_session table, which is the session table when all users browse the page in the foreground.
Both tables are memory tables (memory tables read and write much faster than MYISAM tables and text files).

In discuz! The session in X is inseparable from the cookie, because the session is a cookie that is read from the client,
The associated function executes when the page is browsed and then writes to the database SESSION table.

I use the login process as an example to explain how the program is executed.
On the front page, click Login, pop up a login window, fill in the data, submit. The URL of the form form submission is:
Copy the Code code as follows: Http://ux.com/member.php?mod=logging&action=login&loginsubmit=yes&floatlogin=yes &inajax=1
The data is submitted to the member.php file, and the following code is visible in the program:

$mod =!in_array ($discuz->var[' mod '), $modarray)? ' Logging ': $discuz->var[' mod '); The MoD value is the next loaded PHP page define (' Curmodule ', $mod); $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/member_ '. $mod. PHP '; To complete a program's include operation

Open the source/module/member/member_logging.php file, which is a class, and you can see the following three lines of code in front of the class:

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

if (!submitcheck (' Loginsubmit ', 1, $seccodecheck)) {//Judgment statement is when a visitor browses, the return value of the Submitcheck function is false, reversed, and true. When the user logs on, the program goes to the Else section, where you can see the following five lines of code:} else {  $_g[' uid '] = $_g[' member ' [' uid '] = 0;  $_g[' username ' = $_g[' member ' [' username '] = $_g[' member ' [' password '] = '; Variable assignment  $result = userlogin ($_g[' gp_username ', $_g[' Gp_password '], $_g[' Gp_questionid '], $_g[' Gp_answer '], $_g[' Setting ' [' Autoidselect ']? ' Auto ': $_g[' Gp_loginfield '); Query the user data from the database and return the appropriate information  if ($result [' status '] > 0) {//Status value greater than 0, indicating that this user can log in   

Let's take a look at the Setloginstatus function in source/function/function_login.php, which is an ordinary write COOKIE operation that is no longer specifically explained:

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 ' [' invisible '] = getuserprofile (' invisible ');  $_g[' member '] = $member;  $_g[' core ']->session->isnew = 1;  Dsetcookie (' auth ', Authcode ("{$member [' password ']}\t{$member [' UID ']}", ' ENCODE '), $cookietime, 1, true); Authcode encryption  Dsetcookie (' Loginuser ');  Dsetcookie (' Activationauth ');  Dsetcookie (' Pmnum '); }

It can be said that most of the login process has been completed, but the cookie does not clear, will always exist in the client, if the timeout, the program will be judged to discard this COOKIE, and re-write.

Let's take a look at the class of SESSION operations in DZX, in the source/class/calss_core.php file:
Each request in the program loads the session, which is performed by the _init_session method in the core class Discuz_core, which is placed in the Init method of the class, stating that each time the class is loaded, the session is automatically written.

function _init_session () {$this->session = new Discuz_session ();//Create Session class if ($this->init_session) {//from C Ookie Read Data $this->session->init ($this->var[' cookie ' [' Sid '], $this->var[' ClientIP '], $this->var['   UID ']);   $this->var[' sid '] = $this->session->sid;   $this->var[' session '] = $this->session->var; Determine if the SID is equal, unequal, indicating that multiple users are logged on to the Web site on the same host, and need to re-write the COOKIE if ($this->var[' SID ']! = $this->var[' cookie ' [' SID ']) {Dsetcook   IE (' 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 '); }//uid is not empty and needs to update session or session timeout, change user state, require user to re-login if ($this->var[' UID ') && ($this->session->isne W | | ($this->session->get (' lastactivity ') + < TIMESTAMP)) {$this-&GT;SESSION-&GT;set (' lastactivity ', TIMESTAMP);    $update = Array (' lastip ' = = $this->var[' clientip '), ' lastactivity ' + TIMESTAMP);    if ($this->session->isnew) {$update [' lastvisit '] = TIMESTAMP;   } db::update (' Common_member_status ', $update, ' uid= '). $this->var[' uid ']. "'"); }  } }

The class that operates the SESSION is discuz_session, and we look at two methods within this class:

This function is responsible for generating a new session, but is not responsible for writing database function create ($IP, $uid) {//create session, execute Insert data, generate a six-bit random number by random function that is the SESSION's unique value time is the current time, Sid   $this->isnew = True for SIDs in cookies;   $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 is responsible for updating 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);   

At this point we know the specific function of the SESSION inserted into the database, the connection with the COOKIE, but it is not clear how this action is triggered.
Open the source/function/function_core.php file, locate the function, Updatesession, this function is responsible for updating 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; }

We search this function in the source code of the program, we can see that in many templates there is the following sentence:
Copy the Code Code as follows: {eval updatesession ();}
This function is triggered when the page is browsed and the SESSION is written to the database.

Organize your thoughts:

The first step: User login, the program will write cookies to the client, these cookies are part of the SESSION data, such as Sid, IP, time, does not include the user name, password and other key information.

Second, after the login is successful, the program automatically refreshes the page, sends the request to the server again, the server loads the Discuz_core core class, and reads the information from the COOKIE to the SESSION, but has not yet written to the database.

The third step, the core class loading complete, the program continues to execute, finally loading the template, triggering the Updatesession function, SESSION is written to the database.

I hope this article is helpful to everyone's 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.