How to keep the session in PHP principle and program Introduction _php skills

Source: Internet
Author: User
Tags http cookie php and sessions

How to keep the session in PHP and some of the thoughts arising from it the recent project, which has a relatively large form, the user to complete it takes a lot of time, many users spent painstakingly completed, a submission found session expired, the system exited, So it's the need to study how to set up sessions and keep session online, and here are some insights.

What is session?
According to the wiki explanation, the session is the interaction information that exists between two communication devices, which is established at a certain time and is invalidated after a certain period of time. Common sessions are: TCP session, WEB session (HTTP session), LOGIN session, and so on.

According to the OSI model, sessions are implemented in different locations, the session is mainly divided into several types, one is the application-level session, including Web sessions (HTTP session) and Telnet remote login session; Initiation Protocol (SIP) and Internet Phone call; TCP sessions are implemented at the transport layer.

This article mainly discusses web session, there are generally two types: client session and server-sidesessions, the latter one of the most common belongs to the Java beans provided.

What does the session do?
In the computer field, especially the network, the session is used particularly widely, also can be called Dialogue (dialogue), sessions, etc., generally refers to the two communication devices stored between the state, and sometimes occurs between the user and the computer (Login session).

Unlike stateless communication, the session is usually used to store the communication state, so that at least one party to the communication needs to store the history of the session to achieve communication between the two.

How is the session (WEB session) implemented?
HTTP communication between browsers and servers typically contains an HTTP Cookie to identify the state, usually with a unique SESSIONID, which typically records some of the user's authentication information and levels.

The most commonly used HTTP session token in several programming languages is Jsessionid (JSP), Phpsessid (PHP), ASPSessionID (ASP), which is typically generated by a hash function that uniquely represents the user's identity. When the server and the client communicate, the parameters as get or post are stored on the client.

There are usually two ways to implement a session, server-side session and client session, both of which have their advantages and disadvantages.

Server-side session implementation is easy and efficient, but when it comes to load balancing or high availability requirements, it is difficult to deal with, which is not available when there is no storage device in the internal system. Load balancing can be achieved by sharing a file system or forcing customers to log on to only one server, but this can reduce efficiency. For devices that do not have storage, you can also use RAM (reference reference 6) to resolve server-side session implementations, which are valid for which clients link limited systems (such as routing or access point devices).

The use of client session can solve some problems of server session, such as avoiding the algorithm of load balancing, but it also produces some problems of its own. The client session uses cookies and encryption techniques to save the state between different requests. At the end of each dynamic page, the current session is counted and sent back to the client. After each successful request, the cookie is sent to the server side to "Remember" the user's identity. The most important problem with client session is security, and once the cookie is hijacked or tampered with, the security of the user's information is lost.

How do I set the session in PHP?
After building PHP's development environment, you can view the session-related sections through Phpinfo () including:
Session module, in the PHP V5.2.9 version, a total of 25 variables. One of the usual settings in the regular use of several are:

Copy Code code as follows:

Session.cookie_lifetime sets the cookie expiration time to store SessionID Session cookie Name, default is PHPSESSID
Session.save_handler The session is stored by default to file
Session.save_path Fedora The following defaults are stored in/var/lib/php/session
Session.gc_maxlifetime These three options are used to deal with the probability of a GC mechanism happening
Session.cache_limiter (Nocache,private,private_no_expire,public)
Session.cache_expire These two options are used to cache the session page

The first question, how long will the session expire, and how does he expire? If you want to use the session in the PHP program, you must first refer to Session_Start (), the function of the execution, will be in the session of the storage directory (if using the file handler) to generate a session file, the contents are empty, The browser also meets a cookie named Phpsessid, which stores a hash of the session's name.

The expiration of the session depends on a garbage collection mechanism (garbage Collection), which is stored as a file on the server after the session is created, and the access time of the session file is updated every variable that is accessed by the client script. Each visit is based on the SessionID of the client store to request the only session stored in the server, when the client's cookie expires, you can not know what is to access the sessions, although at this time the server is not expired on the end of the process file, This can lead to a waste of server resources.

But at the same time, if we want the user's session to expire immediately, we can do it by setting up cookies. The session is recycled every time the page is accessed, the probability of recycling is specified by Session.gc_probability,session_gc_divisor, the default 1/100. If set to 1, the session will be recycled each time it exceeds the lifetime of the sessions.

Two types of requirements:
1, to maintain the session is not a period of time or to extend the expiration period;
2, the session expires immediately.

1. It is very necessary to keep the session and extend the expiration of sessions, especially in internal application systems or when there are large forms. Think of your boss filling out a form, just meet lunch time, keep this form and so eat back, fill out the remaining content, submitted after what he saw, generally is a login interface. To improve the user experience, the key is to keep the boss's form out of the question, we have to extend the session's life cycle.

Keeping session expiration and prolonging the sessions expire can be done by setting up Session.gc_maxlifetime, but first you need to ensure that the client's cookie does not expire before the GC performs the recycle. It is possible to extend the lifetime of the session by setting a longer gc_maxlifetime, but it is clearly not the best choice for a server configuration for applications that are not always kept for a long time.
We know that the session's recycling mechanism is based on the session file's last access time to judge, if more than maxlifetime, the recovery rate according to the rate of recovery. So we just need to visit the session regularly, and this can be achieved by refreshing the page, according to this idea, the solution is there.

Through JS regular access to the page;
Use the IFRAME to refresh the page periodically;

Directly using the program to send HTTP requests, so that you can avoid embedding other elements in the page;

The following is the use of JS to send a request to achieve the session is not a period of implementation, so that we only need to keep the sessions to maintain a long time of the page (such as large form page).

Copy Code code as follows:

<script type= "Text/javascript" >
function Keepmealive (imgname) {
myimg = document.getElementById (imgname);
if (myimg) myimg.src = MyImg.src.replace (/\?.) *$/, '? ' + math.random ());
Window.setinterval ("keepmealive (' phpimg ');", 4000);

After the URL is added a random number is to avoid this link request is cached by the browser.

2, so that the session immediately expired method is more, we can Session_destroy (), can also use the above ideas, request a Session_destroy page.

Is the session secure?
PHP's Manual is clearly written: The session does not guarantee that the information stored in the session must only be seen by his creator.

If you want to handle some remote operations securely, HTTPS is the only option. The most basic, do not think that a user information exists in the session that the user must be himself, although the session of the information will give you he has been the user name and password verification of the illusion. So, if you need to do some changes to the password or similar things, let the user re-enter the password is a better choice.

The early Apache version did not use cookies to store phpsessid, but rather the url-rewrite that followed each URL with phpsessid=<sessionid> To indicate that it belongs to the active session, and the new Apache has set this property to the default shutdown.

Copy Code code as follows:

session.use_trans_id = 0;

So in this sense, prolonging the session too long or keeping the session online is never a good thing for security. The ultimate solution is for users to submit a jump to the login window, and then return to fill out the page, and all the data is still there. The implementation of this method is now resolved with Ajax it should not be difficult to post the current user data to a storage location, whether XML or JSON, at a certain time.

A method that can be used for situations where the client does not support javascript:
1, write a floating layer, displayed at the top level, if the user does not disable JS, then let the floating layer disappear;
2, all the input are set to disable, and then use JS set to Enabled;
The above two methods are in JS is disabled, all functions can not be used, how in JS is disabled in the case of our application is still normal work, this seemingly more difficult. The time it takes to achieve this and the results you receive are weighed down.

Related Article

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.