The difference between a session and a cookie---

Source: Internet
Author: User
Tags php session

The biggest difference between a session and a cookie is that the session is stored in the server's memory.

And the cookie is saved with the browser or client file inside;

Session is an access-based process that records the beginning and end of an access, and when the browser or process is closed, the session disappears.

and cookies are more used for labeling, which can be long-term for users to track and identify unique users.


About session, is used to indicate a continuous link state, in the site access generally refers to the client browser from the open to the end of the process.

The session is actually the access visits variable for the site analysis, which represents a process of access.

Browser area multi-process session sharing: A session cookie is shared with multiple tabs or pages when multiple processes access the same site, and is cleared only if the browser is closed, or you may have closed the hack website in the tag. However, as long as the browser is not closed and the server session does not expire before restarting the site, then the session is used to browse.



Session is an HTTP protocol-based mechanism to enhance web application capabilities or a scenario, not a specific dynamic page technology, which is the ability to maintain state (keep painting).

In many dynamic website developers, the session is a variable, and it behaves like a black hole, he only need to put things in the right time in the hole, and so on when necessary to take out the things. This is the most intuitive way for developers to feel about the session, but what about the scene in the black hole or the inside of the session?

In many dynamic website developers, the session is a variable, and it behaves like a black hole, he only need to put things in the right time in the hole, and so on when necessary to take out the things. This is the most intuitive way for developers to feel about the session, but what about the scene in the black hole or the inside of the session?

The Web application is based on the HTTP protocol, and the HTTP protocol is a stateless protocol. That is, the user jumps from page A to page B to resend the HTTP request, and the server does not know what the user did before requesting the B page when returning the response. There are cookies and sessions to resolve the HTTP protocol's own stateless way. Both can record the state, the former is to save the state data on the client, the latter is saved on the server.

A description of the cookie can be viewed in these two articles: the cookie profile or the difference between the cookie and the session. Today is mainly about the implementation of the session principle.

The basic principle of session is to maintain a session information data for each session of the server, while the client and server rely on a globally unique identity to access session information data. When a user accesses a web app, the service-side program decides when to create the session, which can be summed up in three steps:
1, generate globally unique identifier (SessionID)
2, open up data storage space. It is common to create the appropriate data structure in memory, but in this case, once the system loses power, all session data will be lost, and if it is an e-commerce website, the accident will have serious consequences. However, it can also be written in a file or even stored in a database, although this will increase I/o overhead, but the session can achieve some degree of persistence, and more conducive to the sharing session;
3, the session's globally unique indicator character to the client.

There are two main ways that a server can send a client the unique identity of a session: Cookies and URL rewriting. The difference between a cookie and a session is also written, which is no longer detailed here. Let's start by talking about the session in PHP.

Session ID user session Unique identifier, randomly generated string, with uniqueness, randomness. It is mainly used to distinguish the session data of other users. When a user accesses a Web page for the first time, the PHP session initialization function call is assigned to the current visiting user with a unique ID, also known as session_id.
Session data we will need to save through the session of the user state information, called the user session, also known as session data. This is usually the $_session data used in the current session life cycle.
Session file PHP defaults to storing session data in a file. We refer to the file that holds the session data as the session file. It is set by a special php.ini Session.save_path specify the session file storage path, CentOS5.3 operating system, PHP5.1 by default in the/var/lib/php/session directory. The name of the user session file is prefixed with Sess_, named after session_id, for example, session ID is VP8LFQNSKJVSIILCP1C4L484D3, then the session filename is Sess_ Vp8lfqnskjvsiilcp1c4l484d3
Session Lifetime We start the initialization session until we unregister the session, which is called the session life cycle, which helps us understand the session management function.

Summary: Thus, we can see: When each user accesses the Web, the session initialization function of PHP assigns a unique session ID to the current visiting user. And at the end of the session life cycle, the session data generated by the user during this period is persisted to the session file. When the user accesses again, the session initialization function will read the session data from the session file and start the new session life cycle.

===php.ini settings related to the session:
Session.save_handler = file is used to read/write back the session data by default, files. It allows the session management function of PHP to store session data using the specified text file
Session.save_path = "/var/lib/php/session" Specifies the directory where the session file is saved and can be assigned to a different directory, but the specified directory must have write permissions to the httpd daemon (such as Apache or WWW). Otherwise, the session data cannot be stored back. When the specified directory does not exist, the PHP session environment initialization function will not help you create the specified directory, so you need to manually build the specified directory. It can also be written like this session.save_path = "N;/path" where N is an integer. This allows not all session files to be stored in the same directory, but scattered in different directories. This is useful for servers that handle a large number of session files. (Note: Directories need to be created manually)
Session.auto_start = 0 If this option is enabled, the session will be initialized for each request of the user. We recommend that you do not enable this setting, preferably through the session_start () display to initialize the session
Session-related PHP functions and events
The Session_Start () function Session_Start initializes the session and also marks the beginning of the session declaration cycle. To use the session, you must initialize a session environment. A bit similar to the OOP concept of calling a constructor construct to create an object instance. Session initialization operation, declares a global array $_session, maps the session data that is present in memory. If the session file already exists and the session data is saved, session_start () reads the session data, fills in the $_session, and begins a new session life cycle.
$_session It is a global variable, the type is an array, which maps the session data of the session life cycle, which is in memory. When the session is initialized, the data is read from the session file and filled into the variable. At the end of the session life cycle, write the $_session data back to the session file.
Session_register () registers the global variable name with the current session during the session lifetime using the global variable names. The so-called registration, is to fill the variable into the $_session, the value is null. It does not perform any IO operations on the session file, but only affects the $_session variable. Note that the correct notation for this is session_register (' varname '), not Session_register ($varname).
Session_unregister () is the opposite of the session_register operation, which is to unregister the specified variable from the current session during the session life cycle. Also affects $_session only, and does not perform any IO operations.
Session_unset () in the session life cycle, unregisters all session data from the current session, making $_session an empty array. It differs from unset ($_session) in that unset deletes the $_session variable directly, freeing the memory resource, and the other difference is that session_unset () can manipulate the $_session array only during the SESSION life cycle, and unset () The $_session array can be manipulated throughout the page life cycle. Session_unset () also does not perform any IO operations, affecting only the $_session array.
Session_destroy () If you say Session_Start () Initializes a session, it unregisters a session. means that the session life cycle is over. After the session life cycle is complete, session_register, Session_unset, Session_register will not be able to manipulate the $_session array, and the $_session array can still be manipulated by functions such as unset (). At this point, the session means undefined, and $_session is still a global variable, and they are out of the mapping relationship.
SESSION_REGENERATE_ID () invokes it to reassign a new session ID to the current user. And at the end of the current page life cycle, the current session data is written to the session file. The premise is that the current session life cycle is not terminated until this function is called (refer to 9th). It generates an IO operation, creates a new session file, creates a new session file, and creates a new session file immediately before the end of the session, rather than calling this function.
The Session_commit () Session_commit () function is an alias for the Session_write_close () function. It will end the life cycle of the current session and will immediately force the session data to be written to the session file. It is not recommended to manually write session data via Session_commit () because PHP automatically ends the session life cycle that is not currently terminated at the end of the page life cycle. It generates an IO write operation.
End session ends the session, by default, PHP automatically ends the session that is not currently terminated until the end of the page life cycle. However, you can also end the session early with Session_commit () and Session_destroy () two functions. Either way, ending the session will result in an IO operation that is different. By default, an IO write operation is generated to write the current session data back to the session file. Session_commit () invokes the function at the moment, generating an IO write operation to write the session data back to the session file. Unlike Session_destroy (), it does not write data back to the session file, but instead deletes the current session file directly. Interestingly, neither session_commit () or Session_destroy () will not empty the $_session array, nor will it delete the $_session array, except that all session_* functions can no longer manipulate session data. Because the current session life cycle is terminated, you cannot manipulate an undefined object.
How is the ==session ID passed?
The session is in the end because of the management of user status information exists. The session ID is a sign of the user's identity, just like a ticket. Once the user has been assigned a session ID every access (HTTP request) will carry the session ID to the server, to load the user's session data.

The Web communication protocol between client and server is HTTP, while PHP uses HTTP to get user data in three ways: Post method, get method and cookie. The PHP default delivery method is a cookie and is the best method. The session_id is passed through the Get method only when the client does not support cookies (the browser disables the cookie feature), that is, by passing the session ID in the query_string part of the URL.

Session ID transfer process? The user accesses the page through a browser, enters the URL into the address bar, and the browser makes a request, and the browser engine searches for a valid cookie record in the HTTP request header before calling the socket send. The server receives the request and gives it to PHP for processing. At this point, the session initialization function if the element stored with Session_name () as the key value is not found in $_cookie (the value is session_id), a user is the first to access the Web. As a first-time user, session initialization functions randomly generate a session_id and call the newly generated session_id with the Setcookie () function to "session_name = session_id" Format into the HTTP corresponding header Set-cookie field, sent to the client (so that the next request, the HTTP request Cookie field will carry the cookie record as a Web server). If the initialization function discovers that the presence of $_cookie[' sess_name ' is already defined in the client's cookie, the session file corresponding to $_cookie[' Sess_name '] will be reloaded ($_cookie[' Sess_name ') ] is the session ID). If the user cookie record expires, it will be deleted by the browser. After the next request, the server will assume that the user is also the first time to visit, so loop.

================+ "

The difference between a session and a cookie---

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.