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

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

May 27, 2020 pm 03:53 PM
laravel

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,
Copy after login

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);
Copy after login

Use request request

We can get all Session data in this way:

$sessions = $request->session()->all();
Copy after login

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);}
Copy after login

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);
Copy after login

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数据
Copy after login

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;}
Copy after login

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']);
Copy after login

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);
    }
}
Copy after login

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:

<?php
namespace App\Http\Controllers;
use Cookie;
use App\Http\Controllers\Controller;

class DashboardController extends Controller{
    public function index()
    {
        Cookie::queue(&#39;younger&#39;, &#39;Hello, dayang&#39;, 30);
        return view(&#39;welcome&#39;);
    }
 }
Copy after login

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(&#39;younger&#39;);
    dump($cookie);
}
Copy after login

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);
}
Copy after login

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(&#39;younger&#39;));或 \setcookie(&#39;younger&#39;, &#39;&#39;, -1, &#39;/&#39;);
Copy after login

Method 2:

$cookie = Cookie::forget(&#39;younger&#39;);//return Redirect::route(&#39;index&#39;)->withCookie($cookie);
Copy after login

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1244
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles