Home  >  Article  >  Backend Development  >  PHP has to mention sessions and cookies

PHP has to mention sessions and cookies

藏色散人
藏色散人forward
2019-09-11 11:25:552961browse

PHP has to mention sessions and cookies

#What are sessions and cookies?

session and cookies belong to a session control technology. Commonly used in identity recognition, login verification, data transmission, etc. For example, when we go to the supermarket to check out, we have to take out our membership card to get the discount. At this time, how do we identify that this membership card is real and valid? When we give the membership number to the cashier, the cashier inputs it into the system based on the membership number we provided. The system will query based on the membership number. If found, it will prove that the membership number is real. The membership number here is like cookie and session. The membership system is like the server, and the cashier is like the client.

Why are session and cookie used?

Based on the above examples, we know what session and cookie can do, so why must we use this to achieve it? Here it is necessary to understand the characteristics of the http application transfer protocol. Since the http protocol is stateless, that is, the browser requests a web page, which is an http request. When the server receives the request, it returns the data required by the client. During this process, the browser and the server establish an A connected one. But when the server returns data and the client receives the data, their connection relationship is disconnected. The next time the browser sends a request, it will re-establish a connection, and these two links have nothing to do with each other. Just imagine, when we log in to a shopping mall system, we go to the homepage and do the login operation, but when we place an order or add to the shopping cart, we still need to log in. We have to log in every time we visit a page. Isn’t it very cumbersome and also very inconvenient? Scientifically speaking, if we click to place an order after adding a product to the shopping cart, we need to log in to the ordering page and it will not be able to correctly feedback the products when you placed the order.

Http Features

1. The http protocol supports client/server mode and is also a request/response mode protocol.

2. No connection. The so-called connectionless means that after the server receives the client's request, completes the response and receives the client's response, it disconnects the connection. Limit each connection to only process one request. This saves transmission time.

3. Stateless. The http protocol has no memory capability for transaction processing. This means that if the previous information is needed, it can only be retransmitted, which will increase the amount of data transmission. This method liberates the server to some extent, but it is not conducive to the connection between the client and the server. In order to make up for this shortcoming, two technologies for recording http status have been developed, one is called Cookie, and the other is called Session. We will talk about them in detail later.

4. Simple and fast: The so-called simple and fast means that when the client requests services from the server, generally speaking, it only needs to transmit the request method and path to access

5. Flexible: What this mainly refers to is that the client can transmit any type of data through the http protocol. For example, when transferring .jpg files, .ppt files, etc., you only need to set the content-type to transfer.

Cookie

The basic concept of cookie

Cookie is a mechanism for remote browsers to store data to track users and identify users. From the implementation Say, a cookie is a piece of data stored on the client.

Cookie operating principle and storage mechanism

. Operating principle

1. The client initiates an http request to the server.

2. The server sets an instruction to create a cookie and responds to the client.

3. The client receives the instruction from the server and creates a cookie on the client according to the instruction.

4. When blocking the next request, the client carries this cookie and sends a request to the server.

. Storage mechanism

In general, cookies are stored on the client side There are three forms of storage. Different browsers have different storage mechanisms and different cookies.

1. File storage. The browser will create a separate file in the corresponding directory on the disk for different domains to store the cookie value under the domain.

2. Memory storage. This cookie disappears when the browser is closed. According to the creation syntax below, this situation will occur when we do not set the expiration time.

3.flash storage. This storage method is permanently stored on the disk. Even if you delete some data through the browser, the cookies stored in this method cannot be deleted. If you need to delete it, you may use the disk.

Cookie settings

Bool setcookie(string $name[, string $values, $expire=0[,string $path[,string $domain[, bool $secure = false[, bool $httpOnly = false]]]]] );

$name: The name stored in the cookie, required option.

$values: The value stored in the cookie. What needs to be noted here is that when the value is set to false, the client will try to delete the cookie value, so when the value is to be true or false, we use another value instead, for example, 1 for true Instead, false is replaced with 0.

$expire:cookie的过期时间,秒为单位,当该值被设置时,定时删除;当该值没有设置时,该值是永久有效的.该值设置为小于当前时间时,会出发浏览器的删除机制,会自动删除cookie.

$path:cookie有效的目录,默认的目录是"/",即表示当前的正个域名都生效.

$domain:cookie的作用域名,默认的是当前域名有效,如果需要设置直接填写生效的域名即可.需要注意的是IE浏览器有长度限制,当只有大于5的时候才会生效.

$secure:cookie的加密处理,当设置为true的时候,需要使用HTTPS协议,才会生效.

$httpOnly:决定cookie是否只使用http协议,当设置为1或者true,其他非http协议是无法操作cookie的。例如我们未设置的时候,我们JavaScript是可以对cookie进行设置的.这样一定程度上保证了安全性.这种情况需考虑浏览器是否支持该配置项.

. 设置 cookie 的函数还有 setrawcookie () 函数,只不过该函数不会对值 进行 urlencode 序列号.

.ac48bac2b8b96521dcd0023c5193ba8e 有时候,我们可能遇到这种情况,我们在这个页面设置了 cookie,但是去刷新页面获取 cookie,按理说是会获取到 cookie 的,但实际情况是无法获取到,这是由于 cookie 运行机制导致,PHP 创建了 cookie 这个指令,告诉浏览器,你需要执行这个指令了,这时候浏览器才会去执行这个指令,因此是无法获取到 cookie 的.

. 在设置 cookie 之前,不能有任何输出.

// 实现方式一
setcookie($cookie,"hello,world!", 3600);
// 实现方式二
header("header("Set-Cookie: testcookie=中文; path=/; domain=.sunphp.org; expires=".gmstrftime("%A, %d-%b-%Y %H:%M:%S GMT",time()+9600));");
// 两则的作用是一样的,setcookie是PHP内置函数,是对http协议的操作封装。

 cookie 的获取

$_COOKIE['$cookeName'];

 cookie 的应用

. 用户身份识别

. 数据传输

. 登录控制 (是否登录、单点登录)

 cookie 跨域设置

我们都知道,在前端开发中时常会遇到 ajax 跨域问题,我们解决的方式有很多种,可以参考这篇文章传送门 1,传送门 2,cookie 跨域我们可以参考 p3p 传输协议传送门

 cookie 使用的注意事项

. 数量限制,客户端对每一个 domian 下的 cookie 是有数量限制的,不是创建任意数量就行.

. 安全性,根据上面的创建语法,我们可以得知,当我们未设置 $httpOnly 值得时候,非 http 协议是可以操作 cookie 的值的,例如 JavaScript 通过 cookie ($cookieName). 而且一些抓包工具也是可以抓取到 cookie 的,还有就是 cookie 存储在客户端的文件中,如果获取到这个 cookie,也是可以对 cookie 做一些操作的。为了防止别人可以拷贝 cookie 文件,进行恶意操作,可以对 cookie 进行加密处理.

数据传输:当 cookie 数量很多,数据很大的时候,其实对于带宽是有消耗的。比较 http 传输都需要带宽,当 http 传输的数据量大了,带了的带宽消耗就大.

 Session

 运行原理与存储机制

. 运行原理

1. 客户端向服务端发起请求,建立通信

2. 服务端根据设置的 session 创建指令,在服务端创建一个编号为 sessionid 的文件,里面的值就是 session 具体的值 (组成部分 变量名 | 类型 : 长度:值).

3. 服务端将创建好的 sessionid 编号响应给客户端,客户则将该编号存在 cookie 中 (一般我们在浏览器存储的调试栏中会发现 cookie 中有一个 PHPSESSID 的键,这就是 sessionid,当然这个名称,我可以通过设置服务端是可以改变的).

. 当下一次请求时,客户端将这个 sessionid 携带在请求中,发送给服务端,服务端根据这个 sessionid 来做一些业务判断.

. 存储机制

1. 存储方式.session 默认是文件存储的。我们可以通过 php.ini 的配置来设置存储驱动传送门

2. 生命周期。当我们未设置 session 的生命周期时,当浏览器关闭之后存储在客户端的 phpsessid 自动消失,因为它是存在内存,下次建立连接的时候会重新创建一个 phpsessid. 之前的 session,PHP 会自动的根据垃圾回收机制自动删除。这里我们可以根据 session_set_cookie_params ($expire) 函数来设置一个生命周期;

 session 的设置

session_start();
$_SESSION = $values;

. session_start () 设置之前,不能有任何输出

 session 的获取

$_SESSION['values'];

 session 的删除

// 只是单纯的给重新赋了一个空的值
$_SESSION['values'] = '';
// 该函数是清空所有的session,慎用!
session_destroy();
// 连values这个session键都会删除
unset($_SESSION['values']);

 session 的使用场景

. 用户身份识别

. 数据传输

. 登录控制 (是否登录、单点登录)

 session 的注意事项

. 安全性,sessionid 是按照一定的算法生成,要保证 session 的值唯一性和随机性.

. The client disables cookies. According to the operating principle of the session above, it can be concluded that the storage and transmission of the session still depends on the client. Therefore, when the client disables cookies, the client cannot save the PHPSESSID. At this time, you can pass URL rewriting or forms are used to realize session transmission.

. Storage optimization, according to the above session creation, all sessions will be created in a directory, and some invalid sessions will not be deleted within the garbage collection mechanism time. will be deleted. When a server is configured with many sites, many session files will be generated at this time, causing our reading speed to slow down. We can set the storage directory level of the session and save_path function. Generally, large projects (such as distributed project), you can use other storage methods, such as data storage and memory storage.

The difference between session and cookie

. Session is stored on the server side, cookie is stored On the client side.

.cookie creation instructions are set by the server.

.session’s sessionid needs to be stored on the client side.

Several misunderstandings between cookies and sessions

. The client prohibits cookies and the session cannot be used?

Using url rewriting or form submission can achieve this.

. Comparing the security of session and cookie, is session more secure on the client side?

Since cookies exist on the client side, the security is relatively low, but you can set the $httpOnly value when creating.

Since cookies and sessions are related to each other, get Once the cookie has acquired the session to a certain extent, you can also operate the session.

. Will the cookie and session disappear when the browser is closed?

This requires checking the storage mechanism. Cookies can be stored in files, memory, and flash. Of course, if they are stored in memory, they will disappear when the browser is closed; due to the garbage collection mechanism, the session will not be deleted when it is in the garbage collection mechanism, unless the deletion operation is shown in your code.

.Cookies are stored on the client, how to increase their security?

We can add some special parameters when setting the cookie, such as client information IP, browser information, etc. Is it possible to operate even if the file is obtained by the server?

It depends on whether the cookie management mechanism is the same between browsers.

Related recommendations: "

PHP Tutorial

"

The above is the detailed content of PHP has to mention sessions and cookies. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete