Home Web Front-end HTML Tutorial Use the session_set_save_handler function to save the session in the database. After that, the session cannot cross pages_html/css_WEB-ITnose

Use the session_set_save_handler function to save the session in the database. After that, the session cannot cross pages_html/css_WEB-ITnose

Jun 24, 2016 am 11:48 AM

<?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;   }   } ?>
Copy after login

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

See all articles