Home  >  Article  >  PHP Framework  >  The mechanism of session and cookie and related applications under laravel framework

The mechanism of session and cookie and related applications under laravel framework

L
Lforward
2020-05-27 15:53:303283browse

The mechanism of session and cookie and related applications under laravel framework

1. The origin of cookies

When a user visits When accessing a website, the web server will save some 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, it will send the locally recorded information. To display it on the web page, this is the meaning of cookie existence.

So how does the server identify the user? As we all know, the http protocol is a stateless connection. The so-called stateless connection means that every time the browser initiates a request to the server, it does not go through a connection, but establishes a new connection every time. If it is a connection, the server process can maintain the connection and remember some information status in the memory. After each request ends, the connection is closed and the relevant content is released, so no state is remembered and it becomes a stateless connection. For servers based on the http protocol, for different connections, the server cannot identify that these connections are all from the same user, so cookies came into being.

When the server is accessed for the first time, there is no cookie in the http message. At this time, the server instructs the browser to carry the cookie information in the response (response) downstream HTTP message; the browser accesses the same server again. When entering the domain, the cookie information will be carried into the request (request) upstream HTTP request, thereby realizing HTTP simulation and state.

To summarize, a cookie is actually a small piece of text information. The client requests the server. If the server needs to record the user status, it uses response to issue a cookie to the client browser. The client will save the cookie. When the browser requests the website again, the browser submits the requested URL together with the cookie to the server. The server checks this cookie to identify the user's status. The server can also modify the contents of the cookie as needed.

2. Contents and characteristics of cookie

The main content of cookie: name, value, domain, path and expiration time Name and Value attributes are composed of Program settings, the default value is a null reference. The default value of the Domain attribute is the domain name part of the current URL, regardless of which directory the page that sends this cookie is in. The default value of the Path attribute is the root directory, that is, "/", regardless of which directory this cookie is issued. In which directory the cookie page is located. The scope of this cookie can be further limited by the program setting it to a certain path. The Expires attribute sets the expiration date and time of this cookie.

When the Expires attribute is not set, the cookie will automatically Disappears and is called a session cookie. Session cookies exist in memory rather than on the local hard drive. If the expiration time is set, the browser will save the cookie to the hard drive. After closing and opening the browser again, these cookies will still be valid. until the set expiration time is exceeded. Cookies stored on your hard drive can be shared between different processes in your browser.

Cookie features:

1. Cookies are not encrypted and can be tampered with at will, so they are very unsafe

2. Cookies cannot be shared between different domains. The cookie size is limited, as shown below Shown

The mechanism of session and cookie and related applications under laravel framework

3. The birth of session

In order to make up for the fatal shortcoming of cookie insecurity , the session mechanism was born. Session is another mechanism for recording client status. The difference is that the cookie is saved in the client browser, while the session is saved on the server. When the client browser accesses the server, the server records the client information on the server in some form, which is called a session.

When a user connects to the server, the server will establish a session, and the server uses session_id to identify which user is accessing. When a user establishes a session, you can give him a unique cookie when the user authorization is successful. When a user submits a form, the browser will automatically append the user's SessionId to the HTTP header information. When the server completes processing After this form, the results are returned to the user corresponding to the SessionId.

To summarize, the session is encrypted and more secure than cookies. The session creation process is as follows: When creating a session for a client request, the server first checks whether the request contains session_id. If so, the server will After retrieving the session_id, if the server does not store the session_id, create a session_id; if not, create a session for the client and generate a sessionId associated with this session. The value of the sessionId is a value that is neither repeated nor A string that cannot be easily found and forged. This sessionId will be returned to the client in this response for storage.

4. Similarities and differences between cookie and session

Many people say that cookies and sessions are the same thing. The difference lies in whether they are visible to the user. I also agree with this point of view. As a carrier of session, cookies are saved in the local browser. They are easy to operate and store. They can effectively improve server performance (do not occupy memory). However, cookies have shortcomings such as unsafe plain text and limited size. ; The session is saved in the server cache, encrypted, and the session_id size is not limited, but it affects server performance.

Speaking of the connection between cookies and sessions, we have to mention disabling cookies. In the client browser settings, users can disable cookies, because cookies are the carrier of session_id, so once cookies are disabled , then the session cannot be used. But there are two ways to solve the dependency problem. One is URL rewriting, which simply means adding the session_id parameter to the URL address. The other is the form hidden field. The server will automatically modify the form and add a hidden field so that it can be added to the form. The session_id can be passed back to the server when submitting, as shown below:

The mechanism of session and cookie and related applications under laravel framework

Another connection is session sharing. For a single server with multiple websites (same parent domain and different subdomains), we What needs to be solved is the sharing of session_ids from different websites. Since the domain names are different (aaa.test.com and bbb.test.com), and the session_id is stored in their own cookie, the server will think that the access to the two sub-sites comes from different sessions. The solution is to achieve the purpose of cookie sharing by modifying the domain name of cookies to the parent domain name, thereby realizing the sharing of session_id. The disadvantage is that the cookie information between sub-sites is also shared at the same time.

5. Related applications under laravel

session application

In config/session. The configuration in php is as follows:

   '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,

The driver configuration item is used to set the Session storage method. The default is file, which is stored in a file. The file is located in the path configured by the files configuration item, that is, storage/framework/sessions. In addition, Laravel also supports other storage methods:

database: Store Session data in the specified data table, which is set by the configuration item table memcached: Store Session data in Memcached redis: Store Session data in Array in Redis: Store Session data in an array. This configuration is only used in the test environment. To modify the driver configuration, you need to go to the .env file in the project root directory and modify the SESSION_DRIVER option in it.

The lifetime configuration item is used to set the Session validity period, which defaults to 120 minutes. The expire_on_close configuration item is used to set whether to invalidate the Session immediately when the browser is closed. The encrypt configuration item is used to configure whether Session data is encrypted. The lottery configuration item is used to configure the storage location of the recycled Session. The cookie configuration item is used to configure the cookie name that stores the Session ID. The default is laravel_session. The path configuration item is used to configure the cookie storage path to store the Session ID. The default is the project root directory. The domain configuration item is used to configure the cookie storage domain name that stores the Session ID. The secure configuration item is used to configure whether the Session ID is sent to the server only under the HTTPS protocol.

Use session function

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

Use request request

We can get all Session data in this way:

$sessions = $request->session()->all();

We can access Session data like this:

$request->session()->put('site', 'https://www.php.cn/');if($request->session()->has('site')){
    $site = $request->session()->get('site');
    dd($site);}

In addition, we can also get Session data like this (if the corresponding Session does not exist, return the default value):

$sitename = $request->session()->get('sitename','Laravel');dd($sitename);

In addition, you can Use the push method to push multiple data to the Session array:

$request->session()->push('site.xxx', 'https://www.php.cn/');$request->session()->push('site.xxx', 'Laravel');if($request->session()->has('site')){
    $site = $request->session()->get('site');
    dd($site);}使用pull方法,获取数据后删除使用flush方法,一次性删除所有session数据使用forget方法,删除某个session数据

One-time session

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

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

This will always be valid no matter how the Session data is refreshed. In addition, you can also specify which Session data is valid:

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

You can also compile laravel code yourself:

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); // 启动session
            $request->setSession($session);
        }
        $response = $this->app->handle($request, $type, $catch); // 调用controller的method
        if ($this->sessionConfigured()) {
            $this->closeSession($session);         //关闭session
            $this->addCookieToResponse($response, $session);
        }
        return $response;
    }
    ...
 
    protected function closeSession(SessionInterface $session)
    {
        $session->save();    // 保存session
        $this->collectGarbage($session);
    }
}

Cookie application

Add Cookie

For example, we need to set a cookie value of "Hello, Laravel" in the controller and set the validity period to 10 minutes. It is recommended to use the cookie queue method Cookie::queue() here, because the cookie will be automatically added to the response:

Getting Cookie

The use of cookies is inseparable Response and Request. There are two levels to obtain the value of Cookie, one is the server and the other is the client. If you want the server to get the value of the Cookie, you need to get it from the Request:

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

If you want to get the value of all Cookies, you can use the method without passing parameters:

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

Clear Cookie

The method of clearing Cookie is relatively simple. The principle is the same as setting Cookie, except that the expiration time is set to the past. Here you also need to add Cookie to the HTTP Response, using the make() or forget() method:

Method 1:

\Cookie::queue(\Cookie::forget('younger'));或 \setcookie('younger', '', -1, '/');

Method 2:

$cookie = Cookie::forget('younger');//return Redirect::route('index')->withCookie($cookie);

For more laravel framework technical articles, please visit laravel tutorial!

The above is the detailed content of The mechanism of session and cookie and related applications under laravel framework. For more information, please follow other related articles on the PHP Chinese website!

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