PHP basic tutorial seventeen session technology COOKIE, SESSION

黄舟
Release: 2023-03-06 09:12:01
Original
1517 people have browsed it

Preface

When we use PHP to develop the backend, we need to save some data, and our usual approach is to Saving of the database, but sometimes we do not need to save it in the database. For example, when we log in to the web page, the time of our last visit to the website is displayed on the website. This time of the last visit does not need to be saved in the database. At the same time, after logging in to a certain web page, we save the login user name. We do not need to save these in the database, but use the session technology in PHP to solve it.

Introduction to sessions

PHP's cookie technology and session technology are both for sessions. The session here can be understood as when a user opens a browser and visits a website. From the time the user accesses the website to the end when the user closes the website page, we call it a session. During a session, a user can click on various hyperlinks on the website pages, multiple times.

When we visit a website and the pages within the website, we will launch the website. It's just a session.

Cookie explanation

Sometimes when we visit a website, we can see on the web page the time we last visited the current website as soon as we enter the website. How many. This time can be saved using cookies.

Cookie is a client-side technology. The server writes each user's data to the user's respective browser in the form of a cookie. When users use a browser to access web resources on the server, they will bring their own data with them. In this way, the web resources handle the user's own data. Note that cookie technology is a file written on the browser side. At the same time, cookies are saved in the form of key-value pairs.

PHP basic tutorial seventeen session technology COOKIE, SESSION

As can be seen from the above flow chart, if a cookie is to be created in the server's PHP file, the server encapsulates the cookie creation information into the response header of the http protocol To transfer information, the browser analyzes the response header after receiving it. It knows that the server needs to create a cookie in the browser, and creates a cookie file locally through the information in the response header. When the browser visits this website again, it will Local cookie information is sent to the server.

Cookie:user=abc; PHPSESSID=v6ntsa42f4v0h5jpaoa1tot8r6
Copy after login

Use of cookies

Regarding the use of cookies, it can be simply understood as the operation of adding, deleting, modifying and checking cookies.

Creation of cookie

Creating a cookie is actually very simple

<?php
    //通过setcookie函数进行cookie的创建
    setcookie(&#39;username&#39;,&#39;abc&#39;,time()+3600);
Copy after login

We create a cookie through the setcookie() function, and the cookie will be saved in the browser in the server's cache.

Set-Cookie:username=abc; expires=Mon, 17-Oct-2016 08:55:51 GMT; Max-Age=3600
Copy after login
  • setcookie(parameter 1, parameter 2, parameter 3) We can see in the code that three parameters are passed in this function,

    1. The first parameter is the name of the key to save the information.

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

    3. The third parameter is the time the cookie is saved, and the time saved here is the current Add 3600 seconds to the time. When this time is exceeded, the cookie will expire.

#When we finish executing the above code, we can see the created cookie file in the browser's cache file, which contains our saved data.

username
abc
www.lijiafei.com/test3/
1536
2120470400
30550100
480638768
30550092
*
Copy after login

Reading of cookies

We have saved the data above. The purpose of saving the data is to read the data, and reading the cookie can be understood as :

  1. When the browser requests a page of a website, according to the http protocol: The browser will send the cookie information of the website to the request page of the server through an http request.

  2. After the server receives the cookie information, it will be encapsulated into the $_COOKIE array.

  3. We read from the $_COOKIE array.

    <?php
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        //自动封装到这个数组里面
        var_dump($_COOKIE);
        //通过键名取出值。
        $username = $_COOKIE[&#39;username&#39;];
        echo $username;
        ......结果.......
        array(3) {
          ["user"]=>
          string(3) "abc"
          ["username"]=>
          string(3) "abc"
          ["PHPSESSID"]=>
          string(26) "v6ntsa42f4v0h5jpaoa1tot8r6"
        }
        abc
    Copy after login

    When we access the file, the cookie information is passed through the request header.

    Cookie:user=abc; username=abc; PHPSESSID=v6ntsa42f4v0h5jpaoa1tot8r6
    Copy after login

Cookie modification

When we want to modify the value of a cookie, we still use setcookie to complete the modification, but if the cookie If it does not exist, create it; if it already exists, modify it.

<?php
//通过setcookie函数进行修改,但是如果浏览器没有cookie则进行创建。
setcookie(&#39;username&#39;,&#39;abc123&#39;,time() + 1600);
Copy after login

When we read the value of the cookie, we can see that the value inside has been successfully modified.

array(3) {
  ["user"]=>
  string(3) "abc"
  ["username"]=>
  string(6) "abc123"
  ["PHPSESSID"]=>
  string(26) "v6ntsa42f4v0h5jpaoa1tot8r6"
}
abc123
Copy after login

Cookie deletion and destruction

When we can no longer use the cookie, we can manually destroy the cookie value.
Deleting 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
    //使用setcookie这个函数进行删除
    setcookie(&#39;username&#39;,&#39;&#39;,time()-1);

    //删除保存在$_COOKIE里面的数据
    if(isset($_COOKIE[&#39;username&#39;])){
        unset($_COOKIE[&#39;username&#39;]);
    }

    //删除保存在浏览器中这个网站的所有的cookie
    foreach ($_COOKIE as $key => $value) {
        setcookie($key,$value,time()-1);
    }
    //销毁所有数据
    unset($_COOKIE);
Copy after login

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

In-depth understanding of cookies

The above are the most basic operations of cookies. But there are still many things we need to pay attention to:

  1. 一个Cookie只能标识一种字符串信息,它至少含有一个标识该信息的名称(NAME)和设置值(VALUE)。就是说cookie 总是 名=值的形式保存。

  2. 在默认的情况下,我们创建多个的cookie,将保存在同一个文件中.

  3. 一个WEB站点可以给一个浏览器发送多个Cookie,一个浏览器也可以存储多个WEB站点提供的Cookie。

  4. 浏览器一般只允许存放300个Cookie, 每个站点最多存放20个,每个Cookie的大小限制在4K,但是不同的浏览器,情况可能不同。

  5. 如果创建了一个cookie,并将他发送到浏览器,默认情况下它是一个会话级别的cookie(即存储在浏览器的内存中),用户退出浏览器之后即被删除。若希望浏览器将该cookie存储在磁盘上,则需要使用setcookie()函数的第三个参数设置时间,并给出一个以秒为单位的时间。要删除 cookie 需要确保它的失效期是在过去,才能触发浏览器的删除机制。 就是说,我们的cookie默认的生命周期就是一个会话周期。如果希望设置,就需要 setcookie(‘name’, ‘val’, 时间)

  6. 如果希望cookie长久有效,可以这样创建cookie setCookie(“key”,”val”,PHP_INT_MAX);

setcookie()函数

我们可以看到在操作cookie的时候,都是通过setcookie进行不同的设置,但是我们在查帮助文档的时候,可以看到setcookie的参数并不是三个,而是可以七个参数。

bool setcookie ( string $name [, string $value = "" [, int $expire = 0 [, string $path = ""
 [, string $domain = "" [, bool $secure = false [, bool $httponly = false ]]]]]] )
Copy after login

而我们上面使用的就是前三个参数,设置键和值,同时设置保存的时间。

cookie有效路径

在setcookie()函数中第四个参数是控制cookie的有效路径的,当我们不设置的时候,默认的是当前路径和后台路径有效,但是当我们设置成’/’的时候,cookie全站有效。

案例目录结构:

...test
    |_readcookie.php(读取cookie信息)
    |_abc
        |_createcookie.php(创建cookie)
        |_def
            |_readcookie.php(读取cookie);
Copy after login

两个readcookie.php代码一样:

<?php
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    var_dump($_COOKIE);
Copy after login

创建cookie的代码:

<?php
    //创建cookie保存数据
    setcookie(&#39;user&#39;,&#39;abc&#39;,time() + 1600,&#39;&#39;);
    //再创建一个cookie信息,这两个cookie会保存在一个cookie文件里面
    setcookie(&#39;password&#39;,&#39;123&#39;,time() + 1600,&#39;/&#39;);
Copy after login

创建cookie的时候,第一个键值使用默认的有效路径第二个键值使用全站的有效路径。
当访问test目录下的readcookie.php文件时,只能显示password-123的键值信息。

array(1) {
  ["password"]=>
  string(3) "123"
}
Copy after login

cookie域名共享

我们在开发中可能出现在一个网站(www.test.com)下面有两个域(www.a.test.com,www.b.test.com)名,如果我们不对cookie进行设置,这两个域名是不能互相访问对方的cookie的,但是如果我们对cookie进行设置,就可以实现域名共享。而setcookie()的第五个参数就是控制域名共享的。

<?php
    //设置第五个参数表示两个域名可以共享cookie数据。
    setcookie(&#39;username&#39;,&#39;abc&#39;,&#39;&#39;,&#39;&#39;,&#39;.test.com&#39;);
Copy after login

cookie安全传输

在我们在浏览网页的时候,大多数使用的的协议是HTTP协议,但是还有一种协议是HTTPs协议,这种协议比http协议更加安全,在开发中有时候当我们需要对某些重要的cookie数据必须在https协议下才能被传输,这是就会用到setcookie()函数的第六个参数进行设置。

<?php
//第五个参数设置为false表示可以在http协议和https协议下传输。
setcookie(&#39;username&#39;,&#39;abc&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,false);
//第五个参数设置为false表示只能在https协议下传输。
setcookie(&#39;password&#39;,&#39;123&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,true);
Copy after login

cookie的httponly

在默认情况下,cookie值是可以被其他脚本获取的,比如是JavaScript,这是就可能存在安全问题,那我们怎么防止其他脚本来读取cookie呢?

在setcookie()函数的最后一个参数就是控制cookie只能http协议进行读取。

<?php
//最后一个参数,设置为true表示只能是https协议进行读取。
setcookie(&#39;username&#39;,&#39;abc&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,false,false);
Copy after login

上面的就是对会话技术cookie的介绍。在会话技术中还有之中技术也就是session。

session讲解

在我们登录网页时,输入正确的账号和密码后,我们可以使用会话技术的session技术进行保存数据。
Session是服务器端技术,利用这个技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的session文件,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中的其它web资源时,其它web资源再从用户各自的session中取出数据为用户服务

PHP basic tutorial seventeen session technology COOKIE, SESSION

当我们在服务器需要创建一个session的时候,会在服务器创建一个session文件,并且每个会话独享一份session文件,在服务器session文件默认存在在 c:/windows/temp 目录, 但是我们也可以在php.ini中进行修改。当服务器创建session后,会在返回数据的时候把session的id号封装到http协议的响应头中。

SetCookie:PHPSESSID=58j6c68qo6fhn31qrmt6bbrv70; path=/
Copy after login

这个响应信息和创建cookie的信息很想,但是浏览器并不会在浏览器的缓存中创建cookie文件。当浏览器保存住session的ID后,如果又要访问网页,浏览器会把session的ID封装在请求头中发送给服务器。

Cookie:PHPSESSID=58j6c68qo6fhn31qrmt6bbrv70
Copy after login

session操作

session的操作大致也可以分为增删改查四个步骤。
但是不管是什么操作都需要在操作前开启session机制,使用sessio_start()函数进行开启。同时session数据的保存也是通过键值对的方式进行保存的。session保存的数据类型可以是int,float,boolean,string,array,object。

session的创建

<?php
    //开启session机制
    session_start();
    //把数据保存在$_SESSION数组里面。
    $_SESSION[&#39;user&#39;] = &#39;abc&#39;;
Copy after login

先开启session机制,然后把需要的数据保存在$_SESSION数组里面当我们运行代码可以在http协议的响应头中添加了一段话:

Set-Cookie:PHPSESSID=p4lsn4vrdjtmkou1qc3tn3n577; path=/
Copy after login

同时我们也可以参看我们在服务器保存的session文件。

user|s:3:"abc";
Copy after login

session的读取

<?php
    //先开启session机制
    session_start();
    echo &#39;<pre class="brush:php;toolbar:false">&#39;;
    //保存在session里面的数据会自动封装到$_SESSION数组里面
    var_dump($_SESSION);
    ......结果......
    array(1) {
      ["user"]=>
      string(3) "abc"
    }
Copy after login

当我们读取session的数据的时候,先开启session机制,这样服务器就会把session文件里面的数据封装到$_SESSION数组中,从而就可以对数据进行操作。

session的修改

session的修改和cookie的修改是一样的,session怎么创建,就怎么修改,如果数据不存在就创建,如果数据存在就修改。

session的删除

当我们不需要某些session数据的时候,我们可以进行数据的删除,当然,我们可以删除一个数据,也可以删除全部数据,甚至也可以删除session文件。

<?php

    session_start();
    // if(isset($_SESSION[&#39;user&#39;])){
    //  //删除其中一个数据
    //  unset($_SESSION[&#39;user&#39;]);
    // }

    // //通过循环删除全部的数据。
    // foreach ($_SESSION as $key => $value) {
    //  unset($_SESSION[$key]);
    // }
    //删除session文件
    session_destroy();
Copy after login

我们可以根据自己的需求进行不同数据的删除。

从上面的讲解中可以看到操作session的函数并不像cookie一样只是一个函数,关于session的操作函数有许多。

PHP basic tutorial seventeen session technology COOKIE, SESSION

session的深入了解

session启动方式

在上面我们都是使用了session_start()函数来启动session机制,其实PHP给我们提供了两种方式来开启session

  1. 直接在php文件中使用session_start()函数;这种方式比较灵活,推荐使用这种方式。

  2. 直接在php.ini 文件中,配置session.auto_start = 1 设置1就可以自动打开session机制. 默认情况下这个值是 0,这种方式不推荐使用。

session的安全设置

关于session的安全和cookie的安全设置一样,但是session不是通过函数的参数进行设置的,而是在php.ini文件中进行配置的。其中有几个关键的值:

  • session.save_path:session数据保存在服务器的路径。

  • session.cookie_secure:这个参数的作用和cookie很像,在传输给服务器时,是否安全传输,即是否使用https传输。

  • session.cookie_httponly:只能http协议进行读取。

  • session.cookie_domain:在传输给服务器时,有效域名的设置。

上面的参数我们都是直接在php.ini配置里面修改的,这种修改是永久性的,但有时我们要求只是临时的修改php.ini文件,就可以使用ini_set()函数进行配置。ini_set函数可以去临时修改php.ini 的设置,而且设置只对当前的这个会话有影响。但是有一点ini_set函数要在 session_start()前,才能生效.

session的存储机制

在上面我们在使用session的时候,只是简单的进行session_start()函数开启session机制,并且把数据封装到$_SESSION数组里面,但是我们并没有了解其中的过程,数据是怎么存储在数组里面,又是在什么时候保存在session文件中的,当destroy掉session文件的时候又是在哪里进行执行的,都没有了解。

session的存储机制大致可以分为三步,从session_start开始,到一个文件运行结束

PHP basic tutorial seventeen session technology COOKIE, SESSION

在session_start()开启session机制后,

  1. 判断浏览器传过来的数据中是否带有session_id,如果有就使用,没有就创建一个session文件。

  2. 将session文件中的数据读取到$_SESSION数组中。

  3. 启用session的垃圾回收机制,判断哪些session是失效的,删除失效的session文件。

PHP basic tutorial seventeen session technology COOKIE, SESSION

在脚本周期内,我们可以对$_SESSION数组进行增删改查的操作,注意在这里操作的数据并不会对保存在服务器端的session文件有影响。同时如果在这里使用session_destroy(),就会删除session文件并关闭session机制。

PHP basic tutorial seventeen session technology COOKIE, SESSION

At the end of the script, first determine whether the session mechanism is closed. If not, the data in the $_SESSION array will be written to the session file.

The above is the storage mechanism of session. Understanding and mastering the storage mechanism will be very helpful for us to use session.

session GC

In the above storage mechanism, we know that after opening the session mechanism, in the first step, we judge which files are invalid, and then the session will be enabled The garbage collection mechanism (GC) performs recycling, but it does not need to be recycled every time it is turned on. In fact, there are two parameters in the php.ini file that set the probability of enabling gc.

  1. session.gc_probability

  2. session.gc_pisor= 10000

They are a pair, indicating What is the probability of garbage collection? The calculation formula for the probability is session.gc_probability/session.gc_pisor = 1/10000. That is to say, when the session_start() function is called 10,000 times, the garbage collection mechanism will be triggered once.

But we set different probabilities for different websites. For large websites, session.gc_pisor is set larger, such as 10000, medium-sized websites 500-1000, small websites, 200-300, to avoid frequently triggering GC.

Summary

Session technologies cookie and session are still used a lot in PHP development. Understanding the different characteristics of the two technologies allows us to be more flexible in development. to store different data.

The above is the content of session technology COOKIE and SESSION in the seventeenth PHP basic tutorial. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!