Session


brief introduction

Since the HTTP protocol itself is stateless, and the previous request is not associated with the next request, we introduce a session to store user request information to solve problems caused by statelessness in specific scenarios (such as login and shopping). Larravel uses a simple API to handle various session drivers on the back end in a unified way. At present, popular back-end drivers supported out of the box include Memcached Redis And database.

College note: Rather than using PHP's built-in session function, Larave has implemented a more flexible and powerful session mechanism. Please refer to Illuminate\Session\Middleware\StartSession This middleware, so do not try to pass the $_SESSION Method to obtain the session value of the application, which is futile. In addition, there is a problem that everyone is puzzled about. It is impossible to obtain the application session data in the controller constructor of Laravel. This is because Laravel's session passes StartSession The middleware starts. Since the middleware will be executed after the service container registers all services, and the constructors of the controllers are executed when the container registers services, the session has not been started at this time. Where can I get data? The solution is to post the logic of obtaining the session data or introduce the StartSession Middleware executed later.

to configure

The session configuration file is located in config/session.php By default, the session driver used by Larave is file Driver, which is no problem for many applications. In a production environment, you may consider using memcached perhaps redis Drive to obtain better session performance, especially when the same online application is deployed to multiple machines. This is the best practice.

Session drivers are used to define where the requested session data is stored. Larvel can handle multiple types of drivers:

  • file – Session data is stored in storage/framework/sessions Directory;
  • cookie – Session data is stored in a cookie that has been securely encrypted;
  • database – Session data is stored in the database
  • memcached / redis – The session data is stored in the Memcached/Redis cache, with the fastest access speed;
  • array – Session data is stored in a simple PHP array and is non persistent between multiple requests.

Note: Array drive is usually used for Run Test To avoid session data persistence.

Drive preparatory knowledge

data base

When using database As a session driver, you need to set the table to include the Session field. The following is the table structure declaration of the data table:

 Schema::create('sessions', function ($table) { $table->string('id')->unique(); $table->unsignedInteger('user_id')->nullable(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->text('payload'); $table->integer('last_activity'); });

You can use Artisan commands session:table Create this table in the database:

 php artisan session:table php artisan migrate

Redis

Before using Redis as the session driver in Laravel, you need to install it through Composer predis/predis Package. You can use the database Redis connection is configured in the configuration file. In the Session configuration file, connection Option is used to specify which Redis connection the session uses.

For example, I am config/database.php A session connection is configured for Redis in:

Then config/session.php The session driver is configured as redis , corresponding connection Item Pointing database In redis.session to configure:

Note: SESSION_DRIVER=redis stay .env Set in.

In this way, we complete the session driver configuration as redis

Use Session

get data

There are two main ways to process session data in Laravel: global auxiliary functions session , or by Request Instance (Session data will be set to the request instance's session Property).

Request Instance

First of all, we passed the Request Instance to access session data. We can inject dependency on the request instance in the controller method (controller method dependency via Laravel Service Container Automatic injection):

 <? php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserController extends Controller{ /** *Display the properties of the specified user * * @param  Request  $request * @param  int  $id * @return Response */ public function show(Request $request, $id) { $value = $request->session()->get('key'); // } }

When getting data from a session, you can also pass the default value as the second parameter to get Method. The default value is returned when the specified key does not exist in the session. If you pass a closure as the default value to get Method, the closure will execute and return the execution result:

 $value = $request->session()->get('key', 'default'); $value = $request->session()->get('key', function() { return 'default'; });

Global Session Helper Functions

You can also use global PHP functions session To obtain and store session data. If only one string parameter is passed to session Method, the value corresponding to the Session key is returned; If the parameter passed is a key/value key value pair array, save the data to the Session:

 Route::get('home', function () { //Get data from session $value = session('key'); //Specify Default $value = session('key', 'default'); //Store data to session session(['key' => 'value']); });

Note: Request instances and auxiliary functions via HTTP session There is no substantial difference in data processing. Both methods can be used in test cases assertSessionHas Methods.

Get all session data

If you want to get all the data from the session, you can use all method:

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

Judge whether the specified item exists in the session

has Method can be used to check whether a data item exists in a session. If exists and is not null Return if true

 if ($request->session()->has('users')) { // }

To determine whether a value exists in a session, even if it is null If it doesn't matter, you can use exists method. If the value exists exists return true

 if ($request->session()->exists('users')) { // }

Store data

To store data in a session, you can usually use put Method or session Auxiliary function:

 //By calling the put method of the request instance $request->session()->put('key', 'value'); //Through the global auxiliary function session session(['key' => 'value']);

Push data to array Session

push Method can be used to push data to a session whose value is an array. For example, if user.teams The key contains an array of team names. You can push new values to the array like this:

 $request->session()->push('user.teams', 'developers');

Get&Delete Data

pull Method will obtain and delete data from the Session through a statement:

 $value = $request->session()->pull('key', 'default');

One time data

Sometimes you may want to store data that is only valid in the next request in the session. This can be done through flash Method. Session data stored using this method is only valid in subsequent HTTP requests, and will then be deleted:

 $request ->session() ->flash ('status', 'Successful login to Larave Academy!');

If you need to keep the one-time data in more requests, you can use reflash Method, which saves all one-time data to the next request. If you just want to save specific one-time data, you can use keep method:

 $request->session()->reflash(); $request->session()->keep(['username', 'email']);

Delete Data

forget Method to remove the specified data from the session. If you want to remove all data from the session, you can use the flush method:

 $request->session()->forget('key'); $request->session()->flush();

Regenerate Session ID

Regenerating the Session ID is often used to prevent malicious users from performing session fixation Attack (refer to this article for session fixation attacks: http://www.360doc.com/content/11/1028/16/1542811_159889635.shtml )。

If you use the built-in LoginController If you need to regenerate the session ID manually, you can use regenerate method:

 $request->session()->regenerate();

Add custom session driver

Implementation drive

User defined session driver needs to be implemented SessionHandlerInterface Interface, which contains a few methods we need to implement. For example, a session driver based on MongoDB is implemented as follows:

 <? php namespace App\Extensions; class MongoSessionHandler implements SessionHandlerInterface { public function open($savePath, $sessionName) {} public function close() {} public function read($sessionId) {} public function write($sessionId, $data) {} public function destroy($sessionId) {} public function gc($lifetime) {} }

Note: Larravel does not include a directory for containing extensions by default. You can place extensions anywhere. Here we create a Extensions The directory is used to store MongoSessionHandler

Since these methods are not easy to understand, let's quickly go through each method:

  • open The method is used for the file based session storage system. Since Larvel already has a file Session driver, so you don't need to place any code in this method. You can set it as an empty method.
  • close Like the open method, the method can also be ignored, which is not used by most drivers.
  • read The method should return $sessionId The string version of the matched session data does not require any serialization or other encoding to obtain or store the session data from the driver, because Larvel has serialized it for us.
  • write The method should give $data Write to the corresponding $sessionId , such as MongoDB, Dynamo, etc. Again, do not do any serialization operation. Laravel has already handled it for us.
  • destroy Method to remove from persistent storage $sessionId Corresponding data.
  • gc Method destruction is greater than given $lifetime This method can be left blank for systems with expiration mechanisms such as Memcached and Redis.

Registration Driver

After the session driver is implemented, it needs to be registered to the framework. To add additional drivers to the Larravel Session backend, you can use Session Facade On extend method. We're at some Service Provider as AppServiceProvider Of boot Method (you can also re create a new service provider yourself):

 <? php namespace App\Providers; use App\Extensions\MongoSessionHandler; use Illuminate\Support\Facades\Session; use Illuminate\Support\ServiceProvider; class SessionServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Session::extend('mongo', function($app) { // Return implementation of SessionHandlerInterface... return new MongoSessionHandler; }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }

After the session driver is registered, you can click the config/session.php Used in mongo Driven. Go and try it.


give the thumbs-up Cancel Like Collection Cancel Collection

<<Previous: URL generation

>>Next: Form Validation