1. Origin and implementation of Session
HTTP is a stateless protocol. The request of the same client does not correspond to the previous request. That is to say, we cannot confirm on the server whether the two requests are performed by the same user. This makes it difficult for us to remember the user status among multiple requests in some application scenarios, such as e-commerce websites, A user needs to browse the product, add to the shopping cart, place an order, and purchase multiple requests. If the user status cannot be remembered between these requests, the user cannot complete the normal purchase. Therefore, the Session concept is introduced to remember the user status in the request.
There are two implementation mechanisms for the Session. One is the Cookie-based mechanism we usually see, which stores the unique Session ID generated for each user in the Cookie, the Session ID will be added to each request so that the server can determine whether the user is the same. This mechanism requires browser support for cookies (currently supported by browsers by default ); the other method is to rewrite the URL based on the Session ID as a parameter in the URL, so that the Session ID will be included in each request. This method can be used when the browser does not support cookies.
The above two implementation mechanisms are for clients. The server can also store sessions in different media. Common storage methods include files, databases, Memcached, and Redis. Like the cache and queue, Laravel provides a unified interface for different storage services, next we will look at how to implement Session storage, access, deletion, and more usage in Laravel.
2. Session configuration
The Session configuration file in Laravel is located in config/session. php. The default settings are as follows:
Return [
'Driver '=> env ('session _ driver', 'file '),
'Lifetime' => 120,
'Expire _ on_close '=> false,
'Enabled' => false,
'Files '=> storage_path ('framework/session '),
'Connection' => null,
'Table' => 'session ',
'Lottery' => [2,100],
'Cookies' => 'laravel _ session ',
'Path' => '/',
'Domain '=> null,
'Secure '=> false,
];
The driver configuration item is used to set the Session storage mode. The default value is file, that is, the file is stored in the path configured for files, that is, storage/framework/sessions. Laravel also supports other storage methods:
Database: stores Session data in a specified data table, which is set by the configuration item table.
Memcached: stores Session data in Memcached.
Redis: Store Session data in Redis
Array: stores Session data in an array. This configuration is only used for testing environments.
To modify the driver configuration, go to the. env file in the root directory of the project to modify the SESSION_DRIVER option.
The lifetime configuration item is used to set the Session validity period. The default value is 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 the Session data is encrypted.
The lottery configuration item is used to configure the recycle Session storage location.
The cookie configuration item is used to configure the Cookie name for storing the Session ID. The default value is laravel_session.
The path configuration item is used to configure the Cookie storage path for storing Session IDs. By default, it is the project root directory.
The domain configuration item is used to configure the Cookie for storing the Session ID to store the domain name.
The secure configuration item is used to configure whether to send the Session ID to the server only under the HTTPS protocol.
Store sessions using databases
You need. modify SESSION_DRIVER in the env file to database, and then set config/session. change the connection configuration in php to mysql (if the database used is MySQL). The configuration value corresponds to config/database. the configuration items of the connections database in php, or the default value null is not modified.
Then run the following Artisan command in the project Root Directory:
Php artisan session: table
Composer dump-autoload
Php artisan migrate
Generate the Session data table sessions.
Use Memcached/Redis to store Sessions
To use Memcached to store sessions, you only need to change SESSION_DRIVER in the. env file to memcached.
To use Redis to store sessions, you need. in the env file, modify SESSION_DRIVER to redis and then set config/session. modify the connection configuration in php to default (corresponding to config/database. redis host configuration items in php), of course, you can also use the default value null without modification.
Here we use the default configuration without changing (using the file storage Session ).
3. Session usage example
As a matter of fact, we have already come into use Session storage. For example, we will use Session storage when users log on successfully. Here we use Session to store some simple test data.
Use the help function session
You can use the global help function Session to store sessions:
Session (['site' => 'laravelemy Emy. org ']);
Access Method of the corresponding Session:
$ Site = session ('site ');
You can also perform the following operations on the Session array:
Session (['site. Xxx' => 'laravelemy Emy. org ']);
$ Site = session ('site ');
Dd ($ site );
The output is as follows:
Session access in Laravel
Use Request instance
The above is a quick access Session. We can also perform more advanced operations on the Session on the Request instance.
We can obtain all Session data in this way:
$ Sessions = $ request-> session ()-> all ();
We can access Session data like this:
$ Request-> session ()-> put ('Site', 'http: // LaravelAcademy.org ');
If ($ request-> session ()-> has ('site ')){
$ Site = $ request-> session ()-> get ('site ');
Dd ($ site );
}
You can also obtain the Session data as follows (if the corresponding Session does not exist, the default value is returned ):
$ 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', 'http: // LaravelAcademy.org ');
$ Request-> session ()-> push ('site. Xxx', 'laravel ');
If ($ request-> session ()-> has ('site ')){
$ Site = $ request-> session ()-> get ('site ');
Dd ($ site );
}
The corresponding output is:
Session access in Laravel
Of course, the following methods can be used to achieve the same effect:
$ Request-> session ()-> put ('site. Xxx', ['http: // LaravelAcademy.org ', 'laravel ']);
We can use the pull method to retrieve data and delete it:
$ Siteid = $ request-> session ()-> pull ('siteid', 'laravelemy Emy ');
Echo $ siteid;
$ Siteid = $ request-> session ()-> get ('siteid ');
Echo $ siteid;
Only one LaravelAcademy can be printed.
You can also use the forget method to delete the specified Session data:
$ Request-> session ()-> put ('site. Name', 'laravel ');
$ Sitename = session ('site. Name ');
Echo $ sitename;
$ Request-> session ()-> forget ('site. Name ');
$ Sitename = session ('site. Name ');
Echo $ sitename;
Only one Laravel school can be printed.
You can also use the flush method to delete all Session data at a time:
$ Request-> session ()-> flush ();
$ Sessions = $ request-> session ()-> all ();
Dd ($ sessions );
The printed result is an empty array.
One-time Session data
The so-called one-time data is the valid Session data in the next request (only the next time). A common application scenario is the form verification error message. The usage is also very simple. Use the flash method.
For example, we compile the test code in TestController @ session as follows:
Public function session (Request $ request ){
$ Request-> session ()-> flash ('message', 'Welcome to Laravel college! ');
}
Then write the test code in TestController @ sessionx as follows:
Public function sessionx (){
$ Message = session ('message ');
Echo $ message;
}
Then define the routing rules in routes. php as follows:
Route: get ('test/session', 'testcontroller @ session ');
Route: get ('test/sessionx', 'testcontroller @ sessionx ');
Access http://laravel.app: 8000/test/session in the browser, then access http://laravel.app: 8000/test/sessionx, print out:
Welcome to Laravel college!
Refresh the http://laravel.app again: 8000/test/sessionx, the page shows a blank, indicating that the Session data has been destroyed, this is a one-time Session data.
Of course, if we want to keep the one-time Session data valid, we can define the TestController @ sessionx code as follows:
Public function sessionx (Request $ request ){
$ Request-> session ()-> reflash ();
$ Message = session ('message ');
Echo $ message;
}
In this way, the Session data is always valid no matter how the Session data is refreshed. In addition, you can specify the Session data that is valid:
$ Request-> session ()-> keep (['message']);