PHP Basic Tutorial 17 Session technology cookies, sessions

Source: Internet
Author: User
Tags setcookie browser cache

Objective

We use PHP to develop the background, we need to save some of the data, and we usually do is to save the database, but sometimes we do not need to save in the database, such as when we log on to the Web page, the site to show the last time we visited the site, The time of the last visit can not be saved in the database, and we log on to a webpage, save the login user name, which we can not be saved in the database, but using the session technology in PHP to solve.

Introduction to Sessions

PHP's Cookie technology and session technology are all for sessions. The conversation here can be understood as when a user opens a browser, visits a website, starts from the user's visit to the site, and ends with the user closing the Site page, which we call a session. During a session, the user can click on each hyperlink of the site page, which can be clicked multiple times.

When we visit a website and a website inside the page, know we launch this website. is one session.

Cookie explanation

Sometimes when we visit a website, we can see how much time we visited the current website on the Web page as soon as we entered the website. Cookies can be used to save this time.

A cookie is a client-side technology that the server writes each user's data to a user's browser in the form of a cookie. When users use a browser to access Web resources on the server, they take their own data. In this way, the Web resource handles the user's own data. Note that cookie technology is written on the browser side of the file. At the same time, the cookie is saved in the form of a key-value pair.

As can be seen from the flowchart above, if you want to create a cookie in the server's PHP file, the server encapsulates the information that created the cookie into the HTTP protocol's response header, and the browser accepts the response header for analysis. Know that the server needs to establish a cookie in the browser, through the information of the response header to create a cookie file locally, when the browser again visit the site will be the local cookie information sent to the server.

COOKIE:USER=ABC; Phpsessid=v6ntsa42f4v0h5jpaoa1tot8r6

Use of cookies

The use of cookies can be easily understood as the deletion and modification of cookies.

Creation of cookies

Creating a cookie is actually simple

<?php    //The creation of cookies through the Setcookie function    Setcookie (' username ', ' abc ', Time () +3600);

We create a cookie through the Setcookie () function, which is stored in the browser's cache.

SET-COOKIE:USERNAME=ABC; Expires=mon, 17-oct-2016 08:55:51 GMT; max-age=3600
    • Setcookie (parameter 1, parameter 2, parameter 3) we can see in the code that there are three parameters passed in this function,

      1. The first parameter is the name of the key that holds the information.

      2. The second parameter is the value corresponding to the key

      3. The third parameter is the time the cookie is saved, which is saved at the current time plus 3,600 seconds, and the cookie will expire when this time is exceeded.

When we execute the above code we can see the file of the cookie created in the browser's cache file, which has our saved data.

usernameabcwww.lijiafei.com/test3/153621204704003055010048063876830550092*

Reading of Cookies

In the above we have stored the data, the purpose of which we hold the data is to read the data, and the cookie read can be understood as:

    1. When a browser requests a page from a Web site, it is stated in the HTTP protocol that the browser sends the cookie information of the site to the server's request page via HTTP request

    2. Once the server receives the cookie information, it is encapsulated in the $_cookie array.

    3. We read from the $_cookie array.

      <?php    echo ' <pre> ';    Automatically encapsulated into this array    var_dump ($_cookie);    The value is taken out by the key name.    $username = $_cookie[' username ');    echo $username;    ...... The result ...    .. Array (3) {      ["User"]=>      string (3) "ABC"      ["username"]=>      string (3) "ABC"      ["Phpsessid"]= >      string (V6NTSA42F4V0H5JPAOA1TOT8R6)    }    ABC

      When we access the file, we pass the cookie information over the request header.

      COOKIE:USER=ABC; USERNAME=ABC; Phpsessid=v6ntsa42f4v0h5jpaoa1tot8r6

Modification of cookies

When we want to change the value of a cookie, we still use Setcookie to complete the modification, but if the cookie does not exist, it is created and modified if it is already there.

<?php//is modified by the Setcookie function, but is created if the browser does not have a cookie. Setcookie (' username ', ' abc123 ', Time () + 1600);

We are reading the value of the cookie and can see that the value is changed successfully.

Array (3) {  ["User"]=>  string (3) "ABC"  ["username"]=>  string (6) "abc123"  ["Phpsessid"]= >  string (}abc123) "V6NTSA42F4V0H5JPAOA1TOT8R6"

Deletion of cookies, destruction of

When we are not able to use cookies, we can manually destroy the value of the cookie.
Deleting the cookie data can be understood as two steps, 1, delete the cookie file saved in the browser cache, 2, delete the data saved in the server $_cookie array.

<?php    //Use Setcookie this function to delete    Setcookie (' username ', ' ', Time ()-1);    Delete the data stored in $_cookie    if (isset ($_cookie[' username ')) {        unset ($_cookie[' username ']);    }    Delete all cookies that are saved in the browser for this site,    foreach ($_cookie as $key = = $value) {        Setcookie ($key, $value, Time ()-1);    }    //Destroy All data    unset ($_cookie);

We can delete all cookie information by running the above code.

Deep understanding of cookies

Above is the most basic operation of cookies. But there are a lot of things we need to be aware of:

    1. A cookie can only identify a string of information that contains at least one name and set value (value) that identifies the information. This means that the cookie is always stored in the form of a name = value.

    2. By default, we create multiple cookies that will be saved in the same file.

    3. A Web site can send multiple cookies to a single browser, and a browser can store cookies provided by multiple Web sites.

    4. Browsers generally allow only 300 cookies, each with a maximum of 20, each cookie size limit of 4K, but different browsers, the situation may be different.

    5. If a cookie is created and sent to the browser, by default it is a session-level cookie (that is, stored in the browser's memory) that is deleted after the user exits the browser. If you want the browser to store the cookie on disk, you need to set the time using the third parameter of the Setcookie () function and give a time in seconds. To delete a cookie, you need to ensure that its expiration period is in the past before it triggers the browser's removal mechanism. That is, the default life cycle of our cookie is a session cycle. If you want to set it, you need Setcookie (' name ', ' Val ', time)

    6. If you wish the cookie to be valid for a long time, you can create a cookie Setcookie ("Key", "Val", Php_int_max);

Setcookie () function

We can see that when we manipulate cookies, we use Setcookie to make different settings, but when we look at the help document, we can see that the Setcookie parameter is not three, but it can be seven parameters.

BOOL Setcookie (String $name [, String $value = "" [, int $expire = 0 [, String $path = "" [, String $domain = "" "[, BOOL $secure = False [, bool $httponly = false]]] []])

We used the first three parameters, set the key and value, and set the time to save.

Cookie valid path

In the Setcookie () function, the fourth parameter is the valid path of the control cookie, when we do not set, the default is the current path and the background path is valid, but when we set to '/', the cookie is valid all stations.

Case Directory Structure:

... test    |_readcookie.php (read cookie information)    |_ABC        |_createcookie.php (Create cookie)        |_def            |_ readcookie.php (read cookies);

Two readcookie.php code:

<?php    echo ' <pre> ';    Var_dump ($_cookie);

Code to create a cookie:

<?php    //Create a cookie to save the data    Setcookie (' user ', ' abc ', Time () +, ');    To create a cookie information, these two cookies are stored in a cookie file    setcookie (' password ', ' 123 ', Time () + 1600, '/');

When creating a cookie, the first key value uses the default valid path second key value to use the full-site valid path.
When you access the readcookie.php file under the test directory, you can only display the key value information for password-123.

Array (1) {  ["Password"]=>  string (3) "123"}

Cookie Domain name sharing

We may appear in the development of a website (www.test.com) under the name of two domains (www.a.test.com,www.b.test.com), if we do not set cookies, these two domain names are not mutual access to each other's cookies, But if we set the cookie, we can share the domain name. and the fifth parameter of Setcookie () is to control the domain name sharing.

<?php    //Setting the fifth parameter indicates that two domain names can share cookie data.    Setcookie (' username ', ' abc ', ', ', ', '. test.com ');

Safe Transmission of cookies

While we are browsing the web, most of the protocols used are HTTP protocols, but there is also an HTTPS protocol, which is more secure than the HTTP protocol, and sometimes when we need to have some important cookie data to be transmitted under the HTTPS protocol in development, This is set using the sixth parameter of the Setcookie () function.

<?php//The fifth parameter is set to False to indicate that it can be transmitted under the HTTP protocol and HTTPS protocol. Setcookie (' username ', ' abc ', ', ', ', ', ', false);//The fifth parameter is set to False to indicate that it can only be transmitted under the HTTPS protocol. Setcookie (' password ', ' 123 ', ', ', ', ', true);

HttpOnly of Cookies

By default, cookie values can be obtained by other scripts, such as JavaScript, which is a possible security issue, so how do we prevent other script from reading cookies?

The last parameter in the Setcookie () function is that the control cookie can only be read by the HTTP protocol.

<?php//the last parameter, set to TRUE indicates that only the HTTPS protocol is read. Setcookie (' username ', ' abc ', ', ', ', ', false,false);

The above is an introduction to the session technology cookie. Among the conversational techniques is the session.

Session explanation

We can use session technology to save data when we enter the correct account and password when we log in to the webpage.
Session is a server-side technology, using this technology, the server at run time can be used for each user's browser to create a unique session file, because the session for the user browser exclusive, so the user access to the server's Web resources, Can put their own data in the respective session, when the user to access other Web resources on the server, the other Web resources from the user's own session to remove data for the user Service

When we need to create a session in the server, will create a session file on the server, and each session to enjoy one copy of the sessions file, the server session file by default in the C:/windows/temp directory, But we can also make changes in the php.ini. When the server creates a session, the ID number of the session is encapsulated in the response header of the HTTP protocol when the data is returned.

Setcookie:phpsessid=58j6c68qo6fhn31qrmt6bbrv70; path=/

This response message and the information to create the cookie are very much in mind, but the browser does not create a cookie file in the browser's cache. When the browser saves the session ID, the browser wraps the session ID in the request header and sends it to the server if the page is to be accessed again.

Cookie:phpsessid=58j6c68qo6fhn31qrmt6bbrv70

Session operation

The operation of the session can also be divided into four steps to delete and change.
However, no matter what operation you need to open the session mechanism before the operation, use the Sessio_start () function to open. At the same time, the saving of session data is also saved by key-value pair method. The data type stored in the session can be int,float,boolean,string,array,object.

Creation of Session

<?php    //open session mechanism    session_start ();    Save the data in the $_session array.    $_session[' user '] = ' abc ';

Start the session mechanism and then save the required data in the $_session array when we run the code to add a paragraph to the HTTP Protocol's response header:

set-cookie:phpsessid=p4lsn4vrdjtmkou1qc3tn3n577; path=/

At the same time we can also see the session file we saved in the server.

User|s:3: "ABC";

The session reads

<?php    //start session mechanism    session_start ();    Echo ' <pre> ';    The data stored in the SESSION is automatically encapsulated into the $_session array    var_dump ($_session);    ...... The result ...    Array (1) {      ["User"]=>      string (3) "ABC"    }

When we read the session data, we first open the session mechanism so that the server will wrap the data inside the session file into the $_session array so that the data can be manipulated.

Modification of Session

Session changes and cookie changes are the same, the session how to create, how to modify, if the data does not exist on the creation, if the data exists on the modification.

Deletion of Session

When we do not need some session data, we can delete the data, of course, we can delete a data, you can delete all the data, or even delete the session file.

<?php    session_start ();    if (Isset ($_session[' user ')) {////  Delete One of the data    //  unset ($_session[' user ');    }    ////To delete all data by loop.    //foreach ($_session as $key = $value) {    //  unset ($_session[$key]);    }    //delete session file    Session_destroy ();

We can delete different data according to our own needs.

From the above explanation, we can see that the function of the session is not just a function like a cookie, there are many operation functions on the session.

In-depth understanding of the session

Session start Mode

In the above we have used the session_start () function to start the session mechanism, in fact, PHP provides us with two ways to open the session

    1. Using the Session_Start () function directly in a PHP file is a flexible way to recommend this approach.

    2. Directly in the php.ini file, configure Session.auto_start = 1 setting 1 to automatically open the session mechanism. By default, this value is 0 and is not recommended for use in this way.

Security Settings for session

The session security and cookie security settings are the same, but the session is not set by the parameters of the function, but is configured in the php.ini file. There are several key values:

    • Session.save_path:session the path to the server where the data is saved.

    • Session.cookie_secure: This parameter acts like a cookie and is transmitted to the server securely, that is, whether to use HTTPS transmission.

    • Session.cookie_httponly: can only be read by HTTP protocol.

    • Session.cookie_domain: The setting of the valid domain name when transferring to the server.

The above parameters we are directly in the php.ini configuration modified, this modification is permanent, but sometimes we require only temporary modification of the php.ini file, you can use the Ini_set () function to configure. The Ini_set function can be used to temporarily modify the settings of the php.ini, and the settings only affect the current session. But there is a little bit of ini_set function before Session_Start () to take effect.

Storage mechanism of Session

In the above we use the session, just simple session_start () function to open the session mechanism, and the data encapsulated in the $_session array, but we do not understand the process, how the data is stored in the array, Again when to save in the session file, when the destroy dropped the session file and where the execution, did not understand.

Session storage mechanism can be broadly divided into three steps, starting from Session_Start, to a file run end

After Session_Start () opens the session mechanism,

    1. Determine whether the data sent by the browser is session_id, and if so, create a session file without using it.

    2. Reads the data from the session file into the $_session array.

    3. The session garbage collection mechanism is enabled to determine which session is invalid and delete the invalid session file.

In the script cycle, we can do the $_session array of the operation, note that the operation of the data here will not be saved on the server side of the session file has an impact. Also, if you use Session_destroy () here, the session file is deleted and the session mechanism is closed.

At the end of the script, first determine whether the session mechanism is closed, and if it is not closed, the data inside the $_session array is written to the session file.

The above is the session of the storage mechanism, understand and grasp the storage mechanism, we use the session is very helpful.

GC for session

In the above storage mechanism we know that in the first step after opening the session mechanism by judging which are invalid files, then the session will be enabled garbage collection mechanism (GC) for recycling, but not every turn to be recycled, In fact, there are two parameters in the php.ini file, which sets the probability of enabling GC.

    1. Session.gc_probability

    2. Session.gc_pisor= 10000

They are a pair, which indicates the probability of garbage collection, and the probability of the formula is Session.gc_probability/session.gc_pisor = 1/10000, that is, when called 10,000 Times session_start () function, A garbage collection mechanism is triggered once.

But for different sites we set different probabilities, for large sites, Session.gc_pisor set large points, such as 10000, medium website 500-1000, small site, 200-300, avoid frequent triggering GC.

Summarize

Session technology cookies and sessions are still used in PHP development to understand the different features of the two technologies, allowing us to store different data flexibly in development.

The above is the PHP Basic Tutorial 17 of the session technology cookies, sessions, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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: 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.