How to understand session control in PHP

Source: Internet
Author: User
Tags http post session id setcookie
Session control is a way of tracking the user's communication, using session control mainly based on the following points: Because of the stateless nature of the HTTP protocol, the association between two requests cannot be established through the Protocol, and for the data passing between the usual pages get and post, the main processing parameters are passed, Data input two pages of simple data transfer, for a user on the site of multiple pages, a variety of different data, may also have different permissions to cause the page different, different ways of operation, etc., using get and post is very cumbersome.

1.cookie mode

In order to trace the user, it is necessary to mark the user, the idea is that when the user visits the first page of the site, by setting the user's information identity, the Web server to the form of a text file to the user's computer, these files are called cookies, Stored as a key-value pair, when the user accesses the second page of the Web site, the information in the cookie file will be accessed through the HTTP header information, and the user information will be re-verified, thus avoiding the user information being entered on each visit. You can determine whether the access between multiple pages is not the same user.

function to set information to Cookie: Setcookie ($key, $value, $expire, $path, $domain, $secure).

The parameters are: key, value, expiration time (Unix timestamp, default is 0 to close the browser, the cookie disappears), Access cookie path, set on the server after the path of the script to access the cookie (the default is the root directory), access the cookie domain name, Cookies are only enabled for Web pages in the domain name (such as www.example.com) that can access cookies and whether they are https secure connections.

For example, after submitting a form via post, record some information

<?php        if (isset ($_post)) {            $time = time ();            Setcookie (' user ', $_post[' user '), $time +3600);  The time parameter needs to be larger than the current time point to indicate the effective time of the cookie information        s    etcookie (' Data ', array (three-way), $time +1200);  can store various kinds of data     }   after the success of saving cookies, it is convenient to get the value directly into the $_cookie Super Global array by key name, such as Echo $_cookie[' user ', the basic data type supports       The deletion of the cookie is still done through Setcookie, preferably written in the form of a time in advance, or directly write a key name, such as when the user clicks on the exit to do the operation Setcookie (' User ', ' ', ', ', ' -200 ');  Time ahead, relative to the current time  setcookie (' user ');  Shorthand, write-only key name
  2.session mode

The session is similar to a cookie, except that the original information exists on the client side and is now stored on the server side, but generates an identity ID on the client side, which is saved to the user's local cookie by default, so the session is linked to the cookie. In this way, the user first access the information to the Web server, and randomly assigned to the user a fixed-length string (session ID), the user later access to other pages, with this ID to the service side to find the corresponding user data information, so you can track users, The session using cookies is called a cookie-based session.

However, the user can set the browser to disable cookies (although generally do not do so), and some websites will be forced to allow users to open after detection of disabling cookies, but there is such a situation, so that the cookie-based approach is not feasible, You can then pass in a get form with a session ID attached to the URL and, of course, via HTTP POST.

Use of Session

First, use Session_Start () to open a session. Note that for such network functions, there is no output in front of it, even if the <?php identifier is preceded by a space (must have the output can be controlled with Ob_start (), first output to the cache). (Note that sometimes a single sentence of Session_Start () will report a warning, which will be discussed later)

Then, register the session variable, that is, access user information or useful data, do not need to use what function, directly into the $_session Super Global array, such as $_session[' user '] = $_post[[' user '], the data will be saved to a file on the server side, Of course, it could be in cache (Memcache, Redis).

When you jump to another page, the session is also opened on the other page, still session_start (), if the session is already open, the function returns the current session, and if not, re-open.

Finally, the user exits or destroys the dialog for some reason, to unregister these variables. Take four steps:

1. Still open the session first, or jump to another page, return to the existing session again, you need to ensure that there is no output    session_start ();   Turn on or return a session 2. Empties the related variable in the $_session array  unset ($_session[' Robert ')  //Destroys a variable  $_session = Array ();  or destroy session variables all at once 3. Clear the COOKIE stored on the client, and don't forget that the session ID is also on the user's computer if (Isset ($_cookie[session_name ())) {        unset ($_cookie[ Session_name ()]);    Session_name () Gets the name of the Sesion, and the session ID is also the}4 stored in the form of a name and a value    . Completely destroy the information stored to the server Session_destroy ();

After four steps, the session ends.

3. The basic steps for using session control are as follows:

1) Start a session

Call the Session_Start () function, and the function's specific functions can be consulted in the PHP documentation. It is important to note that this function must be called at the beginning of the script that uses the session, and if not, all information saved in that session cannot be used in the script. In addition to manually calling the Session_Start () function, it is also possible to automatically configure PHP automatic calls, which can be used by Google.

2) Register a session variable

After PHP4.1, the session variable is saved in the Super Global array $_session. To create a session variable, simply set an element in the array, such as $_session[' myvar ' = 5;

3) Use a Session variable

To use a session variable is simple, use the $_session array to access the saved session variables, such as Echo $_session[' Mywar '; will print out 5. You must first start a session with the Session_Start () function before using a session.

4) Unregister variables and destroy sessions

Unregister variables directly using unset, such as unset ($_session[' myvar '), how to destroy all session variables at once, you can use unset ($_session); When a session is finished, you should first unregister all variables and then call Session_destroy () to clear the session ID.

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: info-contact@alibabacloud.com 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.