Use of the Laravel session

Source: Internet
Author: User
Tags delete key

Use Laravel to develop the application, copy the original code, the previous code session used $_SESSION , I thought the transplant can be very good to run, because there is no reliance on other components , the results appear this

Undefined variable: _session

The configuration file configuration of the Laravel session app/config/session.php can be used to look at the option settings and annotations available in the session configuration file.

Laravel uses file to implement the session by default. She does not use php native $_session (PHP native SESSION to see php.ini < Span style= "color: #0000ff; font-size:14px;width:auto;height:auto;float:none;" > position ), so omit PHP-related session function , for example session_start () , $_session . Laravel will be in app /storage/session/ Directory writes to session information, so this directory needs to have write permission, no session will not be able to write successfully.

Laravel, in addition to using the default file as the session implementation, also supports cookie , Memcached Redis and 数据库 the back-end drive as the session implementation. When necessary, you also need to implement a session, such as in the public account and user interaction, the session can not be used directly, because each time the server to request, not through the source of the request to identify the user.

Laravel's session brief API

Session API is relatively simple, we look at the Chinese document also probably know how to mean. But there are a few that are not very well understood.

  1. Permanent Save of Session (within the non-expiring range)

  2. Session::p ut (' key ', ' value ');

  3. Native session equivalent to PHP

  4. $_session[' key ' = ' value ';

  5. Get operation

  6. $value = Session::get (' key ', ' default ');

  7. Remove operation and Delete, similar to pop concept

  8. $value = Session::p ull (' key ', ' default ');

  9. Detect if a key exists

  10. Session::has (' users ');

  11. Delete key

  12. Session::forget (' key ');

This correspondence as long as the session is not period, basically is permanently saved, the next HTTP request also exists. Different from the flash concept below.

Flash concept in the session of Laravel

But laravel out a 快闪flash concept, and I got mixed up all of a sudden. This Flash two requests are valid (this time and the next request is valid), regardless of how many times this request takes action.

  1. Save Key,value

  2. Session::flash(' key ', ' value ');

  3. The value method is still the same.

  4. Session::get (' key ');

  5. Refreshes the flash data time and remains to the next request

  6. Session::keep (Array (' username ', ' email '));

This flash concept put is not the same as the concept above.

    • Put: This corresponds as long as the session is not period, basically is permanently saved, the next request also exists.

    • Flash : Saved values, this request can be used, the next HTTP request can be used, and the next one will not exist.

That is, the next time the request is destroyed , will not let the value of the session become more and more large, you can save some temporary data.

Examples of usage scenarios for this scenario are:

    • The user requests the page, the error message appears, redirects to a new page, and the previous data needs to be displayed. (although it can be passed by URL parameters, it may have an XSS vulnerability if handled poorly).

    • The user visited a page, the filter found no permissions, save the current page URL, redirect to the login page, login success, remove the value, redirect to the original page. (You may need to refresh the saved flash data here)

time when the session landed

I naively thought that Session was used::p ut The function can save this variable. So my code writes like this:

  1. class logincontroller { 

  2.  

  3.      public function login () { 

  4.          session::p ut (' key ', ' value ');   

  5.          print_r ( session::all ()  )  //out to see if the put succeeds  

  6.          exit;   //habitual debugging all exit, do not execute subsequent code  

  7.          //return redirect::to (/);  The framework will have subsequent code execution   after return;

  8.     }  

  9. } &nbs P;

Results the next request is not to find this session, and look at the app/storage/session directory is no file generation. There's always something wrong.

Later saw on the network there is a method Session::save() , so I also used the next, incredibly found a successful generation of the session of the file. So I feel that laravel do not have PHP native session, then after the controller should do something, the session will be written to the file, not every put operation is write operation, so that the IO operation is too frequent, affecting performance.

View the code associated with the call. Laravel after compiling, in the bootstrap/compiled.php

  1. class Middleware implements Httpkernelinterface

  2. {

  3. ...

  4. Public function handle (Request $request, $type = httpkernelinterface::master_request, $ Catch = True)

  5. {

  6. $this->checkrequestforarraysessions ($request);

  7. if ($this->sessionconfigured ()) {

  8. $session = $this->startsession ($request); //Start session

  9. $request->setsession ($session);

  10. }

  11. $response =app->handle $this($request, $type, $catch ); //Call Controller's method

  12. if ($this->sessionconfigured ()) {

  13. $this->closesession ($session); //Close Session

  14. $this->addcookietoresponse ($response, $session);

  15. }

  16. return $response;

  17. }

  18. ...

  19. protected function closesession (sessioninterface $session)

  20. {

  21. $session->save (); //Save session

  22. $this->collectgarbage ($session);

  23. }

  24. }

Tip: If you do not know the function call condition, you can change it in the controller and throw new Exception(); then in /config/app.php the debug debug=>true . You can see the call relationship of the function .

As you can see, after the controller is called, the session->save() method is called to save the session actively. This session can be ground to save, if the controller or view in the Write exit; , then the session will not be saved, unless the active writing Session::save() can be saved manually. So in debug debugging when you must pay attention to AH.



Use of the Laravel session

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.