search
HomeWeb Front-endHTML TutorialUse the session_set_save_handler function to save the session in the database. After that, the session cannot cross pages_html/css_WEB-ITnose

<?php/*============================文件说明========================================@filename:     session.class.php@description:  数据库保存在线用户session,实现在线用户功能!@notice:       session过期时间一个小时,因为我们的站点是使用cookie(有效时间是1小时)登录。               因此我们只记录用户登录的时间,而不是刷新一次更新一次               删除数据库中session记录的动作发生在用户超时后执行这个文件或正常退出(session_destory)@database:     database:sessions  field:sessionid(char32),uid(int10),last_visit(int10)=============================================================================*/class session {     private $db; 	private $lasttime=3600;//超时时间:一个小时    function session(&$db) {         $this->db = &$db;        session_module_name('user'); //session文件保存方式,这个是必须的!除非在Php.ini文件中设置了        session_set_save_handler(             array(&$this, 'open'), //在运行session_start()时执行            array(&$this, 'close'), //在脚本执行完成或调用session_write_close() 或 session_destroy()时被执行,即在所有session操作完后被执行            array(&$this, 'read'), //在运行session_start()时执行,因为在session_start时,会去read当前session数据            array(&$this, 'write'), //此方法在脚本结束和使用session_write_close()强制提交SESSION数据时执行            array(&$this, 'destroy'), //在运行session_destroy()时执行            array(&$this, 'gc') //执行概率由session.gc_probability 和 session.gc_divisor的值决定,时机是在open,read之后,session_start会相继执行open,read和gc        );         session_start(); //这也是必须的,打开session,必须在session_set_save_handler后面执行    }       function unserializes($data_value) {         $vars = preg_split(             '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',             $data_value, -1, PREG_SPLIT_NO_EMPTY |             PREG_SPLIT_DELIM_CAPTURE         );         for ($i = 0; isset($vars[$i]); $i++) {             $result[$vars[$i++]] = unserialize($vars[$i]);         }         return $result;     }     function open($path, $name) {         return true;     }     function close() { 	    $this->gc($this->lasttime);        return true;     }    function read($SessionKey){	    $sql = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1"; 		$query =$this->db->query($sql);		if($row=$this->db->fetch_array($query)){		  return $row['uid'];		}else{            return ""; 		}		    }     function write($SessionKey,$VArray) { 	   require_once(MRoot.DIR_WS_CLASSES .'db_mysql_class.php');	   $db1=new DbCom();	  // make a connection to the database... now	   $db1->connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);	   $db1->query("set names utf8");	   $this->db=$db1;       $SessionArray = addslashes($VArray);		$data=$this->unserializes($VArray);	  	    	 		$sql0 = "SELECT uid FROM sessions WHERE session_id = '".$SessionKey."' limit 1"; 		$query0 =$this->db->query($sql0);		if($this->db->num_rows($query0)<=0){			if (isset($data['webid']) && !empty($data['webid'])) { 			   $this->db->query("insert into `sessions` set `session_id` = '$SessionKey',uid='".$data['webid']."',last_visit='".time()."'");			} 		  			return true;		}else{			/*$sql = "update `sessions` set "; 			if(isset($data['webid'])){			$sql .= "uid = '".$data['webid']."', " ;			}			$sql.="`last_visit` = null " 				  . "where `session_id` = '$SessionKey'"; 				 			$this->db->query($sql); */			return true; 		}	    }   function destroy($SessionKey) {      $this->db->query("delete from `sessions` where `session_id` = '$SessionKey'");      return true;    }    function gc($lifetime) {       $this->db->query("delete from `sessions` where unix_timestamp(now()) -`last_visit` > '".$this->lasttime."'");       return true;   }   } ?>

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
Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

How to modify the playback control style of HTML videoHow to modify the playback control style of HTML videoApr 30, 2025 pm 03:18 PM

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

What problems will be caused by using native select on your phone?What problems will be caused by using native select on your phone?Apr 30, 2025 pm 03:15 PM

Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

What are the disadvantages of using native select on your phone?What are the disadvantages of using native select on your phone?Apr 30, 2025 pm 03:12 PM

What are the disadvantages of using native select on your phone? When developing applications on mobile devices, it is very important to choose the right UI components. Many developers...

How to optimize collision handling of third-person roaming in a room using Three.js and Octree?How to optimize collision handling of third-person roaming in a room using Three.js and Octree?Apr 30, 2025 pm 03:09 PM

Use Three.js and Octree to optimize collision handling of third-person roaming in the room. Use Octree in Three.js to implement third-person roaming in the room and add collisions...

What problems will you encounter when using native select on your phone?What problems will you encounter when using native select on your phone?Apr 30, 2025 pm 03:06 PM

Issues with native select on mobile phones When developing applications on mobile devices, we often encounter scenarios where users need to make choices. Although native sel...

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools