Home > php教程 > PHP开发 > How to keep SESSION from expiring in PHP. Principle and solution introduction

How to keep SESSION from expiring in PHP. Principle and solution introduction

高洛峰
Release: 2016-12-24 09:29:58
Original
1294 people have browsed it

How to maintain SESSION in PHP and some thoughts caused by it. A recent project contained a relatively large form. It took a lot of time for users to complete it. After many users spent a lot of hard work to complete it, they found that the SESSION had expired upon submission. The system exited, so it became necessary to study how to set up SESSION and keep SESSION online. Here are some insights.

What is SESSION?
According to the explanation of WIKI, SESSION is the interactive information that exists between two communication devices. It is established at a certain time and expires after a certain period of time. Common SESSIONs include: TCP SESSION, WEB SESSION (HTTP SESSION), LOGIN SESSION, etc.

According to the different locations of session implementation in the OSI model, SESSION is mainly divided into several types. One is the application layer session, including WEB SESSION (HTTP SESSION) and telnet remote login session; the session layer implementation includes Session Initiation Protocol ( SIP) and Internet Phone Call; implemented at the transport layer are TCP SESSION.

This article mainly discusses WEB SESSION. There are generally two types: client-side SESSION and server-side SESSION. The latter is the most common one provided by Java Beans.

What does SESSION do?
In the computer field, especially in the network, SESSION is particularly widely used. It can also be called a dialogue (Dialogue), conversation, etc. It generally refers to the state stored between two communication devices. Sometimes it also occurs between the user and the computer. time (Login SESSION).

Different from stateless communication, SESSION is usually used to store communication status, so at least one of the two communicating parties needs to store the history of SESSION to achieve communication between the two.

How is SESSION (WEB SESSION) implemented?
When HTTP communication is carried out between the browser and the server, an HTTP Cookie is usually included to identify the status. There is usually a unique SESSIONID. SESSION usually records some verification information and levels of the user.

The most commonly used Http Session Tokens in several programming languages ​​are, JSESSIONID (JSP), PHPSESSID (PHP), ASPSESSIONID (ASP). This identifier is usually generated by a hash function and can uniquely represent the identity of the user on the server. When communicating with the client, it is stored in the client as a GET or POST parameter.

There are usually two ways to implement SESSION, server-side SESSION and client-side SESSION. Both methods have their own advantages and disadvantages.

Server-side SESSION is easy to implement and relatively efficient, but it is more difficult to handle when encountering load balancing or high availability requirements. It is also unavailable when there is no storage device in the endogenous system. Load balancing can be achieved by sharing file systems or forcing customers to log in to only one server, but this will reduce efficiency. For devices without storage, server-side SESSION implementation can also be solved by using RAM (see Reference 6). This method is effective for systems with limited client connections (such as routing or access point devices).

The use of client-side SESSION can solve some problems of server-side SESSION, such as avoiding load balancing algorithms, etc., but it will also cause some problems of its own. Client SESSION uses cookies and encryption technology to save state between different requests. After each dynamic page ends, the current SESSION will be counted and sent back to the client. After each successful request, the cookie will be sent to the server to let the server "remember" the user's identity. The most important issue with client SESSION is security. Once the cookie is hijacked or tampered with, the security of the user's information will be lost.

How to set SESSION in PHP?
After setting up the PHP development environment, you can view the SESSION-related parts through phpinfo() including:
SESSION module, in PHP V5.2.9 version, there are a total of 25 variables. Among them, a few that are often used in daily settings are:

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的页面
Copy after login

Let’s consider the first question first, how long does it take for SESSION to expire and how does it expire? If you want to use SESSION in a PHP program, you must first reference session_start(). Once this function is executed, a SESSION file will be generated in the SESSION storage directory (if a file handler is used), and the content inside is empty. At the same time, browse The server will see a cookie named PHPSESSID, which stores a hashed SESSION name.


The expiration of SESSION relies on a garbage collection mechanism (Garbage Collection). After SESSION is created, it is stored as a file on the server. Every time the client script accesses the variables in SESSION, the access time of the SESSION file will be updated. . Each visit requests the unique SESSION stored in the server based on the SESSIONID stored on the client. When the client's cookie expires, it is impossible to know which SESSION is being accessed, although the SESSION file on the server has not yet been accessed. Recycling after expiration will cause a waste of server resources.

但是同时,如果我们希望用户的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保持长时间的页面(比如大表单页面)。

<script type=”text/javascript”>
 function keepMeAlive(imgName){
myImg = document.getElementById(imgName);
 if(myImg) myImg.src = myImg.src.replace(/\?.*$/, ‘?&#39; + Math.random());
}
window.setInterval(“keepMeAlive(‘phpImg&#39;);”, 4000);
 </script>
Copy after login


其中URL后加入一个随机数是为了避免这个链接的请求被浏览器缓存。


2、使SESSION立即过期的方法就比较多了,我们可以session_destroy(),也可以用上面的思路,请求一个session_destroy的页面。

SESSION安全吗?
PHP的手册中明确写出:SESSION并不能保证储存在SESSION中的信息一定只能被他的创建者所看到。

如果想要安全的处理一些远程的操作,那么HTTPS是唯一的选择。最基本的,不要认为一个用户信息在SESSION中存在就认为这个用户一定就是他本人, 虽然SESSION中的信息会给你他已经经过了用户名和密码验证的假象。所以,如果需要做一些修改密码或者类似的事情的时候,让用户重新输入密码是一个比 较好的选择。

早期的Apache版本并没有采用COOKIE的方式来存储PHPSESSID,而是采用的URL-rewrite,也就是每个URL后面都会加上 PHPSESSID=来表明它属于那个激活的SESSION,新版的Apache已经将这个属性设置为默认关闭。

session.use_trans_id = 0;
Copy after login

所以从这个意义上来讲,延长SESSION的时间过长或者保持SESSION一直在线对于安全来说始终不是一件好事情。终极的解决办法就是用户提交跳转到 登录窗口,登录后又能够回到填写页面,并且所有的数据都还在。这个的实现方式现在用Ajax来解决应该没什么困难,每隔一定时间就把当前的用户数据 POST到一个存储位置,不管是XML或者JSON。


拾遗:
对于客户端不支持JavaScript的情况可以采用的方法:
1、写一个浮层,显示在最顶层,如果用户未禁用JS,则让浮层消失;
2、将所有的INPUT都设置为disable,然后再用JS设置为enabled;
以上这两种方式都是在JS被禁用的时候,所有功能都不能用,如何在JS被禁用的情况下使我们的应用仍然正常工作,这个貌似就比较困难。实现这个的所花的时间和所收到的效果大家要权衡一下。

更多PHP中怎样保持SESSION不过期 原理及方案介绍相关文章请关注PHP中文网!

Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template