search
HomeBackend DevelopmentPHP Tutorialdiscuz session mechanism_PHP tutorial
discuz session mechanism_PHP tutorialJul 13, 2016 pm 05:45 PM
discuzphpsessioncodeexistmechanismofexplain

Php code
Explanation of SESSION mechanism in Discuz! X

As always in Discuz!

​You can see two SESSION tables in the database:
​ One is pre_common_adminsession, which is the SESSION table for the administrator to log in to the background;
The other is the pre_common_session table, which is the SESSION table for all users when they browse the page in the foreground.
Both tables are memory tables (the read and write speed of memory tables is much higher than that of MYISAM tables and text files).

In Discuz! Then the related function execution is triggered when browsing the page, and then written to the database SESSION table.

I will use the login process as an example to explain how the program is executed.
On the homepage of the front desk, after clicking Login, a login window will pop up. After filling in the data, submit it. The URL for form submission is:

1 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 can be seen in the program:
01 $mod = !in_array($discuz->var['mod'], $modarray) ? 'logging' : $discuz->var['mod']; //The value of mod is what is loaded next php page
02 define('CURMODULE', $mod);
03 $modcachelist = array('register' => array('modreasons', 'stamptypeid', 'fields_required', 'fields_optional', 'ipctrl'));
04 $cachelist = array();
05 if(isset($modcachelist[CURMODULE])) {
06 $cachelist = $modcachelist[CURMODULE];
07 }
08 $discuz->cachelist = $cachelist;
09 $discuz->init();
10 runhooks();
11 require DISCUZ_ROOT.'./source/module/member/member_'.$mod.'.php'; //Complete the inclusion operation of the program

Open the source/module/member/member_logging.php file. It is a class. You can see the following three lines of code in front of the class:


$ctl_obj = new logging_ctl();
$method = 'on_'.$_G['gp_action']; // $_G['gp_action'] is equal to the value of action, which is login
$ctl_obj->$method(); //$ctl_obj->on_login();

The login method can be found in the class. In the method, about line 56, there is the following judgment statement:


if(!submitcheck('loginsubmit', 1, $seccodecheck)) {

The judgment statement is that when a visitor browses, the return value of the submitcheck function is false, and if it is inverted, it is true.
When the user logs in, the program goes through the else part, in which 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 user data from the database and return corresponding information
 
If($result['status'] > 0) { //The status value is greater than 0, indicating that this user can log in
setloginstatus($result['member'], $_G['gp_cookietime'] ? 2592000 : 0); //Set login status, that is, write COOKIE operation. The data in COOKIE is the corresponding data in SESSION, but this function Not responsible for writing SESSION

Let’s take a look at the setloginstatus function in source/function/function_login.php. It is an ordinary 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']['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 at this point, but if the COOKIE is not cleared, it will always exist on the client. If it times out, the program will judge to discard this COOKIE and rewrite it.

Let’s take a look at the classes for SESSION operations in DZX, in the source/class/calss_core.php file:
Each request in the program will load SESSION, which is executed by the _init_session method in the core class discuz_core. This method is placed in the init method of the class, indicating that SESSION will be automatically written every time the class is loaded.


function _init_session() {

$this->session = new discuz_session(); //Create SESSION class

If($this->init_session) {
//Read data from COOKIE
$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 whether the SIDs are equal or not, indicating that multiple users are logging into the website on the same host and need to rewrite the COOKIE
If($this->var['sid'] != $this->var['cookie']['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');
         } 
//UID is not empty, and the SESSION needs to be updated or the SESSION times out, the user status is changed, and the user needs to log in again
if($this->var['uid'] && ($this->session->isnew || ($this->session->get('lastactivity') + 600)
                  $this->session->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 SESSION is discuz_session. Let’s look at the two methods in this class:


//This function is responsible for generating a new SESSION, but is not responsible for writing to the database
Function create($ip, $uid) {
//Create SESSION, perform data insertion, and generate a six-digit random number by a random function, which is the unique value of the session. The time is the current time, and the sid is the sid in the cookie
$this->isnew = true;
$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);
                                                                            DB::update('common_session', $data, "sid='$data[sid]'");
                                                                                                                                                  dsetcookie('sid', $this->sid, 86400);
         } 
}  

So far we know the specific function of inserting SESSION into the database and its connection with COOKIE, but it is not clear how this operation is triggered.
Open the source/function/function_core.php file and find the function, updatesession. This function is responsible for updating 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;
}

When we search for this function in the program source code, we can see that the following code is found in many templates:


{eval updatesession();}

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

Organize your thoughts:
Step 1: The user logs in, and the program writes COOKIE to the client. These COOKIE are part of the SESSION data, such as SID, IP, and TIME, and do not include key information such as user name and password.
In the second step, after successful login, the program will automatically refresh the page and send another request to the server. The server loads the discuz_core core class and reads SESSION-related information from COOKIE, but it has not yet been written to the database.
In the third step, the core class loading is completed, the program continues to execute, and finally the template is loaded, the updatesession function is triggered, and the SESSION is written to the database.

Author "pz9042"

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478664.htmlTechArticlePhp code The SESSION mechanism in Discuz! The SESSION mechanism that comes with PHP is a set of built-in mechanisms of the system. In the data...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
discuz database error怎么解决discuz database error怎么解决Nov 20, 2023 am 10:10 AM

discuz database error的解决办法有:1、检查数据库配置;2、确保数据库服务器正在运行;3、检查数据库表状态;4、备份数据;5、清理缓存;6、重新安装Discuz;7、检查服务器资源;8、联系Discuz官方支持。解决Discuz数据库错误需要从多个方面入手,逐步排查问题原因,并采取相应的措施进行修复。

discuz是什么意思discuz是什么意思Aug 23, 2023 am 10:27 AM

Discuz是一个功能强大的开源论坛软件,可以帮助用户快速搭建和管理一个社区论坛,提供了一套完整的论坛系统解决方案,Discuz是由名为Comsenz的中国公司开发和维护的,并且在全球范围内广泛使用。Discuz还有一个庞大的用户社区,可以提供技术支持和经验分享。

怎么去掉discuz版权怎么去掉discuz版权Feb 24, 2023 am 09:15 AM

去掉discuz版权的方法:1、找到并打开“header_common.htm”文件,删掉“Powered by Discuz!”内容;2、找到并打开“footer.htm”文件,删掉“Powered by ME”内容即可。

discuz论坛是什么discuz论坛是什么Jul 10, 2023 am 11:03 AM

discuz论坛是一种网络论坛软件,也称BBS,它是一种用于在互联网上建立论坛社区的程序系统。只哟中功能强大的论坛软件,可以帮助用户建立一个专业、完善的论坛社区,并且可以实现多种功能,如搭建用户注册、登录、查看主题、发布帖子、发表评论、设置版主等功能,让用户可以轻松地进行论坛社区的管理和维护。

什么是discuz什么是discuzAug 23, 2023 am 10:24 AM

discuz是一种功能强大、灵活性高、安全稳定的开源论坛软件,是一个基于PHP和MySQL的在线社区平台,提供了一个完整的论坛系统,包括帖子、主题、用户管理、权限控制等功能。Discuz还具备良好的用户体验和界面设计,以及庞大的开发者社区,可以为用户提供帮助和支持。

discuz如何修改头像discuz如何修改头像Aug 08, 2023 pm 03:53 PM

discuz修改头像的方法:1、登录Discuz后台,在网站根目录下找到“admin.php”或者“admin”目录并登录;2、进入用户管理,可以在左侧或者顶部的导航菜单中找到并点击进入;3、搜索用户,使用搜索功能来找到特定的用户;4、修改头像,在编辑页面,可以找到头像的选项并上传新的头像;5、保存修改;6、刷新页面即可。

discuz如何删除模块discuz如何删除模块Aug 08, 2023 pm 02:59 PM

discuz删除模块的方法:1、登录后台管理,通过输入论坛的网址后跟上来进入后台;2、导航到模块管理,在菜单栏中,找到“模块管理”并点击进入;3、选择要删除的模块,在所有已安装模块的列表中,找到需要删除的模块,点击“删除”按钮;4、确认删除;5、清理缓存,在后台页面,找到“更新缓存”按钮并点击。

discuz附件在哪discuz附件在哪Aug 08, 2023 pm 02:08 PM

discuz附件在网站的根目录下,其路径类似于"/home/wwwroot/forum/data/attachment",在这个目录下,每个附件都会有一个唯一的文件名,以确保文件的唯一性和安全性,附件通常是用户在帖子或私信中上传的文件,例如图片、音频或文档,附件的上传和管理是论坛功能的重要组成部分,使用户能够分享和交流各种类型的内容。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.