First, the origin of cookie

When a user visits a website, the Web server will save part of the information to the local computer. When the user visits the website again, the server will check whether the user has logged in to the website. If so, the local information will be sent to the webpage for display, which is the meaning of the existence of cookies.

So how does the server recognize the user? As we all know, HTTP protocol is stateless connection, the so-called stateless connection refers to the browser each time to make a request to the server, not through a connection, but a new connection. If it is a connection, the server process can hold the connection and remember some information state in memory. At the end of each request, the connection is closed and the associated content is released, so no state can be remembered and the connection becomes stateless. The SERVER based on HTTP protocol cannot recognize all the connections from the same user for different connections. Therefore, cookies emerge as The Times require.

When accessing the server for the first time, there is no cookie in the HTTP packet. In this case, the server commands the browser to carry cookie information in the downstream HTTP packet in response. When the browser visits the same domain again, the cookie information will be carried to the request (REQUEST) uplink HTTP request, so as to realize the HTTP simulation has a state.

To summarize, a cookie is actually a small piece of text information. The client requests the server, and if the server needs to record the user state, it issues a Cookie to the client browser using response. The client saves the Cookie. When the browser requests the site again, the browser submits the requested URL along with the Cookie to the server. The server checks the Cookie to identify the user’s state. The server can also modify the contents of the Cookie as needed.

Ii. Content and characteristics of cookie

Cookie main content: name, value, field, path, and expiration time

  1. The Name and Value properties are set by the program and default to empty references
  2. The default value of the Domain attribute is the Domain part of the current URL, regardless of the directory in which the page that issued the cookie is located
  3. The default value of the Path attribute is the root directory, which is “/”, regardless of the directory in which the page that issued the cookie is located. You can further limit the scope of this cookie by programmatically setting it to a path
  4. The Expires property, which sets the expiration date and time for this Cookie

When the Expires attribute is not set, the cookie automatically disappears after the web page is closed. It is called session cookie. Session cookie exists in memory, not in the local hard disk. If the expiration time is set, the browser saves cookies to hard disk, closes the browser and opens the browser again. These cookies remain valid until the expiration time is exceeded. Cookies stored on the hard disk can be shared between different processes in the browser.

Cookie features:

  • Cookies are not encrypted and can be tampered with at will, making them very insecure
  • Cookies cannot be shared between different domains
  • Cookie size is limited, as shown in the figure below

The birth of session

In order to make up for the fatal shortcoming of cookie insecurity, session mechanism was created. Session is another mechanism to record the client state. The difference is that cookies are stored in the client browser, while session is stored on the server. When the client browser accesses the server, the server records the client information on the server in a form called a session.

When a user connects to the server, the server establishes a session and identifies the user with the session_id. When a user establishes a session, a unique cookie can be given to the user upon successful authorization. When a user submits a form, the browser will automatically attach the user’s SessionId to the HTTP header information. When the server processes the form, Returns the result to the user corresponding to the SessionId.

To summarize, sessions are encrypted and more secure than cookies. The process for creating a session is as follows: When creating a session for a client request, the server first checks whether the request contains the session_ID. If it does, the server retrievals the session_ID. If the server does not store the session_ID, the server creates a session_ID. If not, a session is created for the client and a session ID associated with the session is generated. The value of the session ID is a string that is neither repeated nor easily found to mimic. The session ID will be returned to the client for storage in the response.

Similarities and differences between Cookie and session

A lot of people say that cookies and sessions are the same thing, the difference is whether the user is visible or not. I also agree with this point of view. As the carrier of session, cookies are stored in the local browser, which is easy to operate and store and can effectively improve server performance (not occupy memory). However, cookies have disadvantages such as unsafe plaintext and limited size. Session is stored in the server cache, encrypted, session_ID size is not limited, but affects server performance.

When it comes to the connection between cookie and session, it has to be mentioned to disable cookie. In the setting of client browser, users can disable cookie, because cookie is the carrier of session_ID, so once cookie is disabled, then session cannot be used. The server will automatically modify the form to add a hidden field, so that the session_ID can be passed back to the server when the form is submitted, as shown below:

Another link is session sharing. For a single server with multiple sites (same parent domain and different sub-domains), we need to solve the problem of sharing session_id from different sites. Because the domain names are different (aaa.test.com and bbb.test.com) and the session_id is stored in their respective cookies, the server will assume that the access to the two sub-sites is from different sessions. The solution is to change the domain name of cookies to the parent domain name to achieve the purpose of cookie sharing, so as to achieve the sharing of session_id. The downside is that cookie information is also shared between sub-sites.

V. Related applications under Laravel

The session application

Run the following command in config/session. PHP:



    'driver' => env('SESSION_DRIVER'.'file'),
    'lifetime'= >120.'expire_on_close'= >false.'encrypt'= >false.'files' => storage_path('framework/sessions'),
    'connection'= >null.'table'= >'sessions'.'lottery'= > [2.100].'cookie'= >'laravel_session'.'path'= >'/'.'domain'= >null.'secure'= >false,];Copy the code

Driver configuration items used to set up the Session storage mode, the file by default, is stored in the file, the file is located in the path of the configuration files configuration items, namely the storage/framework/sessions. Laravel also supports other storage methods:

  • Database: Stores Session data to a specified data table, which is set by the configuration item Table
  • Memcached: Stores Session data into memcached
  • Redis: Stores Session data to redis
  • Array: stores Session data into an array. This configuration is only used in test environments. To modify driver configurations, go to the root directory of the project.

Lifetime specifies the lifetime of a Session. The default lifetime is 120 minutes. The expire_on_close configuration item is used to set whether to immediately invalidate a Session when the browser closes. Encrypt Configures whether Session data is encrypted. The Lottery configuration item is used to configure the recycling Session storage location. Cookie Configuration item Is used to set the cookie name of the Session ID. The default value is laravel_session. The path configuration item configures the Cookie path for storing Session ids. By default, the Cookie path is the project root directory. The domain configuration item is used to configure the Cookie domain for storing the Session ID. Secure configures whether to send the Session ID to the server only in HTTPS mode.

Using the session function



session(['site.xxx'= >'LaravelAcademy.org']);
$site = session('site');
dd($site);Copy the code

Using Request

We can get all Session data in this way:



$sessions = $request->session()->all();Copy the code

We can access Session data like this:



$request->session(a)->put('site'.'http://LaravelAcademy.org');
if($request->session()->has('site')){
    $site = $request->session(a)->get('site');
    dd($site);
}Copy the code

Alternatively, you can retrieve Session data as follows (return the default value if the corresponding Session does not exist) :



$sitename = $request->session()->get('sitename'.'Laravel college');
dd($sitename);Copy the code

It is also possible to push multiple data to the Session array using the push method:



$request->session() - >push('site.xxx'.'http://LaravelAcademy.org');
$request->session() - >push('site.xxx'.'Laravel college');
if($request->session() - >has('site')){
    $site = $request->session() - >get('site');
    dd($site);
}Copy the code

Use the pull method to obtain data and then delete it. Use the Flush method to delete all session data at a time. Use the forget method to delete a session data

A one-time session

If you want to ensure that one-time Session data is valid, you can define TestController@sessionx as follows:



public function sessionx(Request $request){
    $request->session()->reflash();
    $message = session('message');
    echo $message;
}Copy the code

This way Session data is always valid no matter how it is refreshed. You can also specify which Session data is valid:



$request->session() - >keep(['message']);Copy the code

You can also compile your own Laravel code:



class Middleware implements HttpKernelInterface
{...public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $this->checkRequestForArraySessions($request);
        if ($this->sessionConfigured()) {
            $session = $this->startSession($request); / / start the session
            $request->setSession($session);
        }
        $response = $this->app->handle($request, $type, $catch); // Call method of controller
        if ($this->sessionConfigured()) {
            $this->closeSession($session);         / / close the session
            $this->addCookieToResponse($response, $session);
        }
        return$response; }...protected function closeSession(SessionInterface $session)
    {
        $session->save();    / / save the session
        $this->collectGarbage($session); }}Copy the code

Cookies are used

Add a Cookie

For example, we need to set a “Hello, Laravel” cookie value in the controller and set the validity period to 10 minutes. The queue method cookie ::queue() is recommended here, because the cookie is automatically added to the response:




        

namespace App\Http\Controllers;
use Cookie;
use App\Http\Controllers\Controller;

class DashboardController extends Controller
{

    public function index(a)
    {
        Cookie::queue('younger'.'Hello, dayang'.30);
        return view('welcome'); }}Copy the code

To get a Cookie

Cookie cannot be used without Response and Request. Getting the value of a Cookie has two layers, one on the server and the other on the client. If the server needs to get the Cookie value, it needs to get it from the Request:



public function index(Request $request)
{
    $cookie = $request->cookie('younger');
    dump($cookie);
}Copy the code

If you want to get the values of all cookies, you can use the no-argument method:



public function index(Request $request)
{
    $cookies = $request->cookie();
    dump($cookies);
}Copy the code

Remove the Cookie

The method of clearing cookies is relatively simple. The principle is the same as setting cookies, but the expiration time is set to the past. We also need to add cookies to the HTTP Response using either make() or forget() :



Method 1: \Cookie::queue(\Cookie::forget('younger')); Or \ setcookie ('younger'.' ', -1.'/'); Method 2:$cookie = Cookie::forget('younger');
//return Redirect::route('index')->withCookie($cookie);Copy the code

Refer to the post

segmentfault.com/a/11…

www.cnblogs.com/endles…

blog.csdn.net/sundache…

blog.csdn.net/proglove…

www.zhihu.com/questio…

laravelacademy.org/pos…

www.cnblogs.com/phpper…