How to maintain the SESSION in PHP and some related ideas

Source: Internet
Author: User
Tags http cookie php development environment

What is SESSION?

According to the WIKI, a SESSION is the interaction information between two communication devices. It is established at a certain time and becomes invalid after a certain period of time. Common sessions include tcp session, web session (http session), and login session.

According to the OSI model, sessions are implemented in different locations. sessions can be divided into several types: Application Layer sessions, including WEB sessions (HTTP sessions) and telnet remote logon sessions. sessions are implemented at the SESSION Layer, including Session Initiation Protocol (SIP) and Internet Phone Call; tcp session is implemented at the transport layer.

This article mainly discusses WEB sessions, which generally have two types: Client SESSION and server SESSION. The latter is the most common one provided by Java Beans.

What is a SESSION?

Sessions are widely used in the computer field, especially in the network field. They can also be called Dialogue and SESSION. They generally refer to the state of storage between two communication devices, sometimes it occurs between the user and the computer (Login SESSION ).

Unlike stateless communication, a SESSION is usually used to store the communication status. Therefore, at least one of the communication parties needs to store the SESSION history to implement communication between the two parties.

How is a web session implemented?

When a browser communicates with a server over HTTP, it usually contains an HTTP Cookie to identify the status. Generally, there is a unique SESSIONID, and the SESSION usually records the user's authentication information and level.

The most common Http Session tokens in programming languages are JSESSIONID (JSP), PHPSESSID (PHP), and ASPSESSIONID (ASP). This identifier is usually generated by the hash function, the identity that uniquely represents the user. When the Server communicates with the client, the user is stored as a GET or POST parameter on the client.

There are two methods to implement a SESSION: server-side SESSION and client SESSION. Each method has its own advantages and disadvantages.

Server-side SESSION implementation is easy and efficient, but it is difficult to handle Server Load balancer or high availability requirements. When the endogenous system does not have a storage device, it is also unavailable. Server Load balancer can be achieved through a shared file system or forcing customers to log on to only one server, but this will reduce the efficiency. For devices that are not stored, you can also use RAM (refer to reference 6) to implement server-side sessions, this method is effective for systems with limited client connections (such as routing or access point devices ).

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

How to Set a SESSION in PHP?

After setting up the PHP development environment, you can view the parts related to the SESSION through phpinfo:

SESSION module. in PHP V5.2.9, there are a total of 25 variables. The following are common settings:

Session. cookie_lifetime: Set the cookie expiration time for storing SESSIONID

Session. name: the COOKIE name of the SESSION. The default value is PHPSESSID.

Session. save_handler SESSION storage method. The default value is FILE.

Session. save_path Fedora is stored in/var/lib/php/session by default.

Session. gc_probability

Session. gc_divisor

Session. gc_maxlifetime three options are used to handle the probability of GC mechanism occurrence

Session. cache_limiter (nocache, private, private_no_expire, public)

Session. cache_expire these two options are used to cache the SESSION page

Let's first consider the first question: how long will the SESSION expire? How does it expire? If you want to use the SESSION in a PHP program, you must first reference session_start (). When this function is executed, it will be stored in the SESSION Directory (if file handler is used) generate a SESSION file with empty content. At the same time, the browser will see a cookie named PHPSESSID, which stores the name of a hash SESSION.

SESSION expiration depends on a Garbage Collection mechanism. After a SESSION is created, it is stored as a file on the server. Each time a client script accesses a SESSION variable, the access time of the SESSION file will be updated. Each access request is based on the SESSIONID stored by the client to request the unique SESSION stored on the server. When the client's cookie expires, it cannot know which SESSION to access, although the SESSION file on the server has not been recovered after expiration, this will cause a waste of server resources.

However, if we want the user's session to expire immediately, we can set the cookie. SESSION revocation is performed every time you access the page. The probability of session revocation is specified by SESSION. gc_probability and session_gc_divisor. The default value is 1/100. If it is set to 1, the SESSION will be recycled every time it exceeds the lifecycle of the SESSION.

Two requirements: 1. Keep the SESSION not expired or prolong the SESSION expiration time in PHP; 2. Make the SESSION expire immediately.

1. It is necessary to keep the SESSION in PHP not expired or to extend the SESSION expiration time, especially when there are large forms in the internal application system. Think about the fact that your boss is filling out a form that just happened to meet the lunch time. Keep the form and wait for dinner to come back, fill in the remaining content, and what he will see after submission. Generally, it is a logon interface. To improve the user experience, the key is to keep the boss's form intact, so we must extend the SESSION lifecycle.

In PHP, you can set SESSION. gc_maxlifetime to keep the SESSION from expired and prolong the session expiration time. However, you must first ensure that the client cookie does not expire before gc is recycled. You can extend the session lifecycle by setting a long gc_maxlifetime. However, this is obviously not the best choice for server configuration for applications that require not all requests to be retained for a long time.

We know that the SESSION recovery mechanism is determined based on the last access time of the SESSION file. If maxlifetime is exceeded, the SESSION is reclaimed Based on the recovery probability. Therefore, we only need to regularly access the SESSION, which can be implemented by refreshing the page. Based on this idea, the solution is available.

Regular access to pages through JS;

Use Iframe to regularly refresh the page;

Directly use a program to send an HTTP request, so that other elements are not embedded in the page;

The following is an implementation method that uses JS to send requests to ensure that the SESSION does not expire. In this way, we only need to maintain the SESSION for a long time (such as a large table single page ).

  1. <script type="text/javascript">  
  2.         function keepMeAlive(imgName){  
  3.             myImg = document.getElementById(imgName);  
  4.             if(myImg) myImg.src = myImg.src.replace(/?.*$/, '?' + Math.random());  
  5.         }  
  7.         window.setInterval("keepMeAlive('phpImg');", 4000);  
  8.     </script>  
  9.     "phpImg" src="" width="1" height="1" /> 

A random number is added to the URL to prevent the URL request from being cached by the browser.

2. There are many ways to make the SESSION expire immediately. We can use session_destroy () or the above idea to request a page of session_destroy.

Is SESSION secure?

The PHP manual clearly states that the SESSION cannot guarantee that the information stored in the SESSION can only be viewed by its creator.

If you want to securely handle some remote operations, HTTPS is the only option. Basically, do not think that a user information exists in the SESSION. This user must be himself, although the information in the SESSION will give you the illusion that he has been authenticated by the user name and password. Therefore, it is a good choice to allow users to re-enter the password when changing the password or similar things.

In earlier versions of Apache, PHPSESSID is not stored using cookies, but URL-rewrite is used, that is, PHPSESSID = <sessionid> is added to each URL to indicate that it belongs to the activated SESSION. Apache of the new version has set this attribute to disabled by default.

Session. use_trans_id = 0;

In this sense, it is not a good thing for security to extend the SESSION for a long time or keep the SESSION online. The ultimate solution is to submit the user to jump to the login window. After logging on, the user can return to the fill page and all the data is still there. This implementation method now uses Ajax to solve the problem. It is easy to POST the current user data to a storage location at a certain time, whether it is XML or JSON.


The following method can be used when the client does not support JavaScript:

1. Write a float layer and display it on the top layer. if Javascript is not disabled, the float layer disappears;

2. Set all inputs to disable, and then use JS to enabled;

The above two methods are used when Javascript is disabled and all functions are unavailable. How can we make our applications work normally when Javascript is disabled, this seems quite difficult. We need to weigh the time taken to achieve this and the effect we have received.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.