PHP Cookie Knowledge:

Source: Internet
Author: User
Tags php session setcookie cron script drupal

A: Cookie knowledge:

1, a cookie in your life whether you know what a cookie is, or in your life, you must have used it. Remember when you use a browser to browse the Web, when you want to log in, the page has a remember password or automatic login option, when you choose, you use a cookie. Then the next time you visit the site, you may have automatically logged in, and do not need to re-enter the user name and password, as to how it is implemented, we explained below.

Why is there a cookie? Because the HTTP server is stateless, that is, it does not log any user and connection information. A web site typically wants to be able to identify users, either because the server wants to restrict access to users, or because it wants to associate content with the user's identity. To do this, HTTP uses a cookie that can track the user.

2. The composition of cookie technology
Before we understand how cookies work, let's take a look at the composition of Cookie technology, which consists of 4 parts, as follows:
(1) There is a cookie header line in the HTTP response message;
(2) There is a cookie header line in the HTTP request message;
(3) A cookie file is kept in the client system and managed by the user's browser;
(4) There is a back-end database on the Web site;

3. How Cookies work
After understanding the composition of cookie technology, let's look at how cookies work. The following is a browser in host A to visit the website xxx as an example to analyze how cookies work.

First, host a uses a browser to surf the internet, when host a first visit the XXX website, when the request message arrives at XXX Web server, the Web server will generate a unique identification code (for example: 12345), and as an index in its back-end database to produce a table entry, and Set-cookie: the header line and the value just generated are the headers that set the HTTP response message. So in the HTTP response message header, we can see such a header line--set-cookie:12345.

When host A's browser receives the HTTP response message, it sees the Set-cookie: header, and then the browser adds a line to its local cookie file, including Set-cookie: the identification number in the header line.

Since host A's cookie file already has the table entry for the XXX website, so when host A's browser continues to browse the XXX website, each request a Web page, its browser will be from its cookie file to obtain the XXX website identification code, And put in the HTTP request message in the cookie header line, that is, the first line cookie:12345.

When the server of XXX website receives the HTTP request message containing the first line of the cookie, the server determines the user of the cookie identifier by querying the back-end server, so that the user's information can be directly known (that is, it is known that there is a user who has recently landed on the site).

Note that in the cookie way, the XXX Web server can track host A's activity at that site, and XXX Web site does not need to know who the user of host A is, but it knows exactly what pages the user 12345 visited, in what order, and at what time.

Simply put, a cookie is used to identify a user, who may need to provide a user ID when the user first accesses the site, but in subsequent accesses, the browser passes a cookie header to the server for the server to identify the user. Thus, a cookie can establish a user session layer on a stateless HTTP that allows the server to authenticate the user through a session between the user and the application.

4. Problems caused by Cookies
However, the use of cookies may pose some problems.

First, the user's privacy issues, from the discussion above, we can see that the site can be our cookie identification number, you can know when we did something.

Second, the security of information, from the above discussion, we can be aware that the server did not perform the necessary checks, that is, the server takes out the cookie identification number of the request message containing the first line of cookies, and then to the back-end server query, you can determine the user, Regardless of whether the request message is a message sent by the original host. In other words, if a hostile person gets our cookie identification number, populates the HTTP request message with our cookie identifier, and sends it to the Web server on the XXX website, it can impersonate us to do a lot of things he wants to do and get a lot of information that they want to get.

Second: Some basic knowledge of session

In PHP, the session is a server global variables can be implemented between the page passed, so the session is often used for server-side user login verification, session security is very high, let me introduce the basic knowledge of PHP session.

How long is the session's life cycle?

1: the end of the browser's life cycle ends at the same time, but the archive still exists in/tmp/(Sess_???)

2: The next time you re-open the browser will be reassigned SessionID, if you use session_id () to bring back the previous ID, you will read the remaining in/TMP Sess_???, Retrieve all of your previously set parameters

3: can modify the remaining time of the session file in PHP.ini

Session.gc_maxlifetime = 1440;

After this number of seconds, stored

Data would be seen as ' garbage ' and cleaned up by the GC process

The default is 1440 seconds, 24 minutes

Use the storage path problem noted in the session to see the settings for the session in PHP.ini

[Session]

Session.save_handler = files; Handler used to Store/retrieve data

Session.save_path =/tmp; Argument passed to Save_handler

In the case of files, the

path where data files are stored

The default is in the/tmp directory, this directory is not necessarily true AH!!! It's best to change your PHP installation path, such as c:/php

Thorough understanding of PHP session Mechanism 1.session.save_handler = files

* 1. Session_Start ()

1: session_start () is the beginning of the session mechanism, it has a certain probability to turn on garbage collection, because the session is stored in the file, PHP itself garbage collection is not valid, the session is to delete the collection of files , this probability is based on the configuration of php.ini, but some systems are session.gc_probability = 0, which means that the probability is 0, instead of a cron script to implement garbage collection.

session.gc_probability = 1

Session.gc_divisor = 1000

Session.gc_maxlifetime = 1440//Expiration time default 24 minutes

The probability is session.gc_probability/session.gc_divisor result 1/1000,

It is not recommended to set too small because the session garbage collection is required to check whether each file is out of date.

Session.save_path =//As if different systems are not the same by default, one setting is "N;/path"

This is a random tiered storage, this kind of word, garbage collection will not work, need to write their own scripts

2: session will determine if there is currently $_cookie[session_name ()];session_name () returns the COOKIE key value that holds the session_id, which can be found from php.ini

Session.name = PHPSESSID//default value PHPSESSID

3: generates a session_id if it does not exist, and then passes the generated session_id as the value of the cookie to the client. The equivalent of performing the following cookie operation, note that this step performed the Setcookie () operation, the cookie is sent in header headers, which can not be output, PHP has another function session_regenerate_id () If this function is used, it cannot be output before.

Setcookie (Session_name (),

session_id (),

session.cookie_lifetime,//Default 0

session.cookie_path,//default '/' current program and directory are valid

session.cookie_domain,//default is empty)

4: If there is so session_id = $_cookie[session_name];

Then go to session.save_path the designated folder to find the name ' Sess_ '. session_id () file.

The contents of the read file are deserialized and then placed in the $_session

* 2. Assigning values to $_session

For example, add a new value $_session[' test ' = ' blah '; Then this $_session will only be maintained in memory, when the script execution is finished,

Write the value of the $_session to the folder specified in session_id, and then close the related resource.

At this stage, it is possible to perform changes to the session_id, such as destroying an old session_id and generating a completely new session_id. Half used in custom session operations, character conversions,

For example, Drupal.drupal's anonymous user has a session, and when it logs in, it needs to be replaced with a new session_id

if (Isset ($_cookie[session_name ())) {

Setcookie (Session_name (), ", Time ()-42000, '/');//old session cookie expired

}

SESSION_REGENERATE_ID ();//This step will generate a new session_id

SESSION_ID () returns a new value

3: Write session operation at the end of the script will perform session write operation, the value of $_session written to the session_id named file, may already exist, you may need to create a new file.

4. Destruction of the session session sent by the cookie is generally an instant cookie, stored in memory, when the browser is closed, will expire, if you need to force expiration, such as log out, rather than close the browser, then you need to destroy the session in the Code, the method has A lot

o 1. Setcookie (Session_name (), session_id (), Time ()-8000000,..); /Log out before execution

o 2. Usset ($_session);//This will delete all $_session data, after the refresh, there is a cookie passed, but no data.

o 3. Session_destroy ();//This function is more thorough, delete $_session delete SESSION file, and session_id

When the browser is not closed, refresh again, 2 and 3 will have a cookie to pass, but no data found

2.session.save_handler = user

User-defined session processing mechanism, more intuitive

* Session_set_save_handler (' open ', ' close ', ' read ', ' write ', ' destroy ', ' GC ');

1.session_start (),

Execute open ($save _path, $session _name) Opening session action handle

$save _path in the case of Session.save_handler = files, it is Session.save_path, but if the user is self-determined, the two parameters are not used, directly return True

Reads the data from the read ($id).//This parameter is automatically passed session_id (), which can be manipulated by this value.

2. Script execution End Execution write ($id, $sess _data)//two parameters, very simple

3. If the user needs Session_destroy () execute destroy first. In the 2nd step

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.