Laravel framework session usage tutorial

Source: Internet
Author: User
Tags http request valid


Use Laravel to develop applications and copy the original code. The previous code session used $ _ SESSION, which was supposed to run well after transplantation because it was not dependent on other components, the result shows this

Undefined variable: _ SESSION
The session configuration file of Laravel is configured in app/config/session. php. You can check the option settings and comments available in the session configuration file during use.

Laravel uses file by default to implement session. She does not use php native $ _ SESSION (php native session depends on the location of php. ini), so ignore php-related session functions, such as session_start () and $ _ SESSION. Laravel will write session information in the app/storage/session/directory during running. Therefore, this directory requires write permission. Otherwise, the session cannot be written successfully.

Laravel not only uses the default file as the session implementation, but also supports cookie, Memcached, Redis, and database backend drivers as the session implementation. When necessary, you also need to implement a session by yourself. For example, in the interaction between the WeChat public account and the user, this session cannot be directly used, because each time it is a request from the WeChat server, users cannot be identified by the request source.

Laravel session brief API

The Session API is relatively simple. You may know what it means by reading Chinese documents. But there are a few that are not easy to understand.


// Permanent session storage (within the period of no expiration)
Session: put ('key', 'value ');
 
// Equivalent to the native session of PHP
$ _ SESSION ['key'] = 'value ';
 
// Get operation
$ Value = Session: get ('key', 'default ');
 
// Remove and delete operations, similar to the pop concept
$ Value = Session: pull ('key', 'default ');
 
// Check whether a key exists
Session: has ('users ');
 
// Delete the key
Session: forget ('key ');
As long as the session does not expire, it is basically permanently saved, and the next http request also exists. Different from the following flash concepts.

Flash concept in laravel's session

But Laravel came up with the concept of flash, and I was confused. The two flash requests are valid (this and next requests are valid), regardless of the number of requests for this request.


// Save key and value
Session: flash ('key', 'value ');
 
// The value method is the same
Session: get ('key ');
 
// Refresh the flash data time and keep it to the next request
Session: keep (array ('username', 'Email '));
The concept of flash is not the same as that of put.

Put: as long as the session does not expire, it is basically permanently saved, and the next request also exists.
Flash: saved value. This request can be used. The next http request can be used, and the next request will not exist.
That is to say, the next request will be destroyed when it is used up, and the session value will not become larger and larger. You can save some temporary data.

The following scenarios are used:

When a user requests a page, an error message is displayed. The user redirects to a new page and needs to display the previous data. (Although it can be passed through url parameters, an xss vulnerability may occur if the processing is poor ).
When you access a page, the filter finds that you have no permissions. Save the url of the current page, redirect to the logon page, log on successfully, retrieve the value, and redirect to the original page. (You may need to refresh the saved flash data here)
Time when the session is implemented

I naively thought that the Session: put function can be used to save this variable. So I wrote the following code:


Class LoginController {
 
Public function login (){
Session: put ('key', 'value ');
Print_r (Session: all (); // obtain the result and check whether the put operation is successful.
Exit; // The usual debugging is exit and subsequent code is not executed.
// Return Redirect: to (/); the framework will execute subsequent code after return.
    }
}

As a result, this Session cannot be found in the next request, and no file is generated in the app/storage/session directory. Something is wrong.

Later, I saw a method Session: save () on the network. So I used it and found that the session file was successfully generated. So I felt that Laravel didn't use the native session of php, so some things should be done after the controller to write the session into the file, instead of writing every put operation, in this way, IO operations are too frequent, affecting performance.

View the call-related code. After laravel is compiled


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 the controller's method
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 );
    }
}
Tips: If you do not know the function call situation, you can throw new Exception (); in the controller, and then change the debug in/config/app. php to debug => true. You can see the call relationship of the function.
We can see that after the controller is called, the session-> save () method is called to actively save the session. In this way, the session can be stored. If exit is written to the controller or view, the session will not be saved unless you actively write Session: save () can be manually saved. Therefore, pay attention to debugging in debug mode.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.