Home php教程 php手册 PHP中怎样保持SESSION不过期 原理及方案介绍

PHP中怎样保持SESSION不过期 原理及方案介绍

Jun 06, 2016 pm 08:27 PM
php

本文主要讨论WEB SESSION,其一般有两种:客户端SESSION和服务器端SESSION,后一种最常见的属于Java Beans提供的

PHP中如何保持SESSION以及由此引发的一些思考  最近的一个项目,里面有一个比较大的表单,用户完成它需要很多时间,很多用户花了千辛万苦完成之后,一提交发现SESSION过期,系统退出了,所以引起了研究如何设置SESSION以及保持SESSION在线的需要,下面是一些心得体会。

什么是SESSION?
按照WIKI的解释,SESSION是存在于两个通信设备间的交互信息,服务器空间,在某一时间建立,经过一定的时间后失效。常见的SESSION有:TCP SESSION、WEB SESSION(HTTP SESSION)、LOGIN SESSION等。

根据OSI模型中,会话实现的位置不同,SESSION主要分为几种,一种是应用层会话,包括WEB SESSION(HTTP SESSION)和telnet远程登录session;会话层实现的,包括Session Initiation Protocol(SIP)和Internet Phone Call;在传输层实现的有TCP SESSION。

本文主要讨论WEB SESSION,其一般有两种:客户端SESSION和服务器端SESSION,后一种最常见的属于Java Beans提供的。

SESSION是做什么的?
在计算机领域,特别是网络方面,SESSION使用的特别广泛,也可以称为是对话(Dialogue)、会话等,一般是指在两个通信设备间存储的状态,有时也发生在用户和计算机之间(Login SESSION)。

区别于无状态的通信,SESSION通常用来存储通信状态,因此通信的双方至少有一方需要存储SESSION的历史记录,从而实现两者间的通信。

SESSION(WEB SESSION)是怎么实现的?
浏览器和服务器之间进行HTTP通信时,通常会包含一个 HTTP Cookie 来标识状态,通常会有一个唯一的 SESSIONID ,SESSION通常记录着用户的一些验证信息和级别。

在几中编程语言中最常用的Http Session Token是,JSESSIONID(JSP),PHPSESSID(PHP),ASPSESSIONID(ASP),这个标识通常由哈希函数产生,能够 唯一表示这个用户的身份,在服务器和客户端通信时,作为GET或者POST的参数存储在客户端。

SESSION的实现方式通常有两种,服务器端SESSION和客户端SESSION,两种方式各有优缺点。

服务器端SESSION实现容易并且效率比较高,但是遇到负载均衡或者高可用性需求的时候,处理起来就比较困难,对于那种内生系统不存在存储设备的时候, 也是不可用的。负载均衡可以通过共享文件系统或者强制客户只能登录到一台服务器上来实现,但是这样会降低效率。对于没有存储的设备,也可以通过使用 RAM(参考参考资料6)来解决服务器端SESSION的实现,香港虚拟主机,这种方法这对哪些客户端链接有限的系统有效(诸如路由或者接入点设备)。

客户端SESSION的使用可以解决服务器端SESSION的一些问题,比如避免了负载均衡的算法等,但是同时也会产生一些自身的问题。客户端 SESSION使用Cookie和加密技术来在不同的请求间保存状态。在每一个动态页面结束后,会统计当前的SESSION,并把它发回客户端。每次成功 请求后,会把cookie再发送到服务器端,来让服务器“记起”这个用户的身份。客户端SESSION最重要的问题就是安全问题,一旦cookie被劫持 或者篡改了,用户的信息的安全性就丧失了。

PHP中如何设置SESSION?
搭建好PHP的开发环境后,通过phpinfo()可以查看到与SESSION有关的部分包括:
SESSION模块,在PHP V5.2.9版本中,一共有25个变量。其中,平时设置中常会用到的几个有:

复制代码 代码如下:


session.cookie_lifetime 设置存储SESSIONID的cookie过期时间
session.name SESSION的COOKIE名称,默认为PHPSESSID
session.save_handler SESSION的存储方式,虚拟主机,默认为FILE
session.save_path Fedora下面默认存储在/var/lib/php/session
session.gc_probability
session.gc_divisor
session.gc_maxlifetime 这三个选项用来处理GC机制发生的机率
session.cache_limiter (nocache,private,private_no_expire,public)
session.cache_expire 这两个选项是用来缓存SESSION的页面


先来考虑第一个问题,SESSION多久会过期,他是如何过期的?如果要在PHP程序中使用SESSION,一定要先引用 session_start(),这个函数一执行,就会在SESSION的存储目录(如果使用了file handler)生成一个SESSION文件,里面内容是空的,同时浏览器会见里一个name为PHPSESSID的cookie,里面存储着一个 hash出来的SESSION的名字。

SESSION的过期依赖于一个垃圾回收机制(Garbage Collection),SESSION创建后作为一个文件存放在服务器上,客户端脚本每访问一次SESSION中的变量,SESSION文件的访问时间 就会进行更新。每次访问都是根据客户端存储的SESSIONID去请求服务器中存储的唯一的SESSION,当客户端的cookie过期后,就无法知道要 访问的是哪一个SESSION,尽管此时服务器上的SESSION文件还没有被过期收回,这样就会造成服务器资源的浪费。

但是同时,如果我们希望用户的session马上过期的话,我们就可以通过设置cookie的办法来实现。SESSION的回收是在每次访问页面的时候进 行的,回收的机率由session.gc_probability,session_gc_divisor指定,默认士1/100。如果设置为1,则每次 超过了SESSION的生存周期去访问的话,SESSION一定会被回收。

两种需求:
1、保持SESSION不过期或延长SESSION过期时间;
2、使SESSION立即过期。

1、保持SESSION不过期和延长SESSION过期时间非常必要,特别是在内部应用系统中或者有很大的表单的时候。想想你的老板在填写一个表单,刚好 碰上午饭时间,留着这个表单等吃饭回来,填写完剩余的内容,提交后他看到什么,一般来说都是一个登录界面。想要提高用户体验,关键是要让老板的表单不出问 题,我们就必须延长SESSION的生存周期。

保持SESSION不过期和延长SESSION过期时间,可以通过设置session.gc_maxlifetime来实现,不过首先需要保证客户端的 cookie不会在gc执行回收之前失效。通过设置一个较长的gc_maxlifetime可以实现延长session的生存周期,可是对于不是所有请求 都会保持很久的应用来说,这么做对于服务器配置显然不是一个最佳的选择。
我们知道SESSION的回收机制是根据SESSION文件的最后访问时间来判断的,如果超过了maxlifetime,则根据回收机率进行回收。所以我们只需要定期的去访问一下SESSION就可以了,而这可以通过刷新页面来实现,根据这个思路,解决的方法就有了。

通过JS定期的去访问页面;
利用Iframe定期的刷新页面;

直接利用程序发送HTTP请求,这样就可以避免在页面中嵌入其他的元素;

下面是利用JS发送请求实现的保持SESSION不过期的实现方法,这样我们就只需要在需要SESSION保持长时间的页面(比如大表单页面)。

复制代码 代码如下:

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles