1. Introduction
Because HTTP-driven applications are stateless, we use the session to store user request information. Laravel uses a clean, unified API to handle a variety of back-end session drivers, and currently supports popular back-end drivers including memcached, Redis, and databases.
Configuration
The session configuration file is located in the config/session.php
. By default, the drive used by Laravel is session
file-driven, which is not a problem for many applications. In a production environment, you might consider using memcached
or redis
driving to get faster session performance.
session
The driver defines where the session data for the request is stored, and laravel can handle multiple types of drives:
file
–session data is stored in the storage/framework/sessions
directory;
cookie
–session data is stored in an encrypted and secure cookie;
database
–session data is stored in the database
memcached
/ redis
–session data is stored in Memcached/redis;
array
–session data is stored in a simple PHP array and is non-persistent across multiple requests.
Note: Array drivers are typically used to run tests to avoid session data persistence.
Session Driver Readiness Knowledge
Database
When using database
session driver, you need to set the table containing session
item, the following is the table structure declaration of the data table:
Schema::create (' Sessions ', function ($table) { $table->string (' id ')->unique (); $table->integer (' user_id ')->nullable (); $table->string (' IP_Address ', ()->nullable (); $table->text (' user_agent ')->nullable (); $table->text (' payload '); $table->integer (' last_activity ');});
You can use the Artisan command session:table
to generate the migration:
PHP Artisan session:tablephp Artisan Migrate
Redis
Before using Redis as a driver in Laravel session
, you need to install the package through composer predis/predis
. Redis connections can be configured in the database configuration file, and in the session configuration file, the database option specifies which Redis connection to use for the session.
2. Use Session
Get Data
There are two main ways to process session data in Laravel: a global auxiliary function session, or a request instance. First, we access the session data through the request instance, which can be introduced by type hints in the Controller method, remembering that the Controller method relies on automatic injection through the Laravel service container:
<?phpnamespace App\http\controllers;use Illuminate\http\request;use App\http\controllers\controller;class Usercontroller extends controller{ /** * Displays the properties of the specified user * * @param Request $request * @ param int $id * @return Response * * public function Showprofile (Request $request, $id) { $value = $request->session ()->get (' key '); // }}
When fetching data from the session, you can also pass the default value as the second parameter to the get
method, and 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 the get
method, the closure executes and returns the execution result:
$value = $request->session()->get(‘key‘, ‘default‘);$value = $request->session()->get(‘key‘, function() { return ‘default‘;});
Global helper Function session
You can also use the global PHP function session
to get and store the data in the session, if only a string argument to the session method, then return the value corresponding to the session key; If the passed parameter is an array of Key/value key values, Then save the data to the session:
Route::get (' Home ', function () { //Get data from session ... $value = Session (' key '); Specify default values ... $value = Session (' key ', ' Default '); Store data to session ... session ([' key ' = ' value ']);});
Note: There session
is no substantial difference between processing data through HTTP request instances and auxiliary functions, both of which can be tested in test cases by assertSessionHas
means of methods.
Get all session values
If you want to get all the data from the session, you can use the all
method:
$data = $request->session ()->all ();
Determine if a specified item exists in the session
has
Method can be used to check whether the data item exists in the session. Returns if it exists and is not NULL true
:
if ($request->session ()->has (' users ') { //}
You can use the method to determine whether a value exists in the session, even if it is null. exists
Returns True if the value exists exists
:
if ($request->session ()->exists (' users ') { //}
Storing Data
Once you get to the session instance, you can call multiple methods to interact with the underlying data, for example, by put
storing new data in the session:
By the Put Method $request->session ()->put (' key ', ' value '),//through the Global helper function session ([' key ' = ' = ' value ']);
Push data to array session
push
The An array method can be used to push data to a session whose value is an array, for example, if the user.teams
key contains a team group, you can push the new value into the array like this:
$request->session()->push(‘user.teams‘, ‘developers‘);
Get and delete data
pull
Method will fetch and delete the data from the session:
$value = $request->session ()->pull (' key ', ' default ');
Disposable Data
Sometimes you may want to store data that is only valid in the next request in the session, and can be implemented by means of a flash
method. Session data stored using this method is only valid in subsequent HTTP requests and will then be deleted:
$request->session()->flash(‘status‘, ‘Task was successful!‘);
If you need to keep this one-time data in more requests, you can use the method reflash
, which holds all the one-time data to the next request, and if you just want to save a particular disposable data, you can use the keep
method:
$request->session()->reflash();$request->session()->keep([‘username‘, ‘email‘]);
Delete Data
forget
Method removes the specified data from the session, and 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 session ID is often used to prevent a malicious user from using a session fixation attack on an application (refer to this article for a session fixation attack: http://www.360doc.com/content/11/1028 /16/1542811_159889635.shtml).
If you use built-in LoginController
, Laravel will automatically regenerate session IDs during authentication, and if you need to regenerate session IDs manually, you can use the regenerate
method:
$request->session ()->regenerate ();
3. Add a custom session driver
Implementation Drive
The custom session driver needs to implement the SessionHandlerInterface
interface, which contains a little bit of the method we need to implement, such as a MongoDB implementation as follows:
<?phpnamespace App\extensions;class Mongohandler 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: Laravel default does not come with a directory to include extensions, you can place extensions anywhere, where we create a Extensions
directory for storage MongoHandler
.
Since these methods are not very easy to understand, let's go through each method quickly:
open
method is used for file-based session storage system, because Laravel already has a file
session driver, so there is no need to put any code in the method, you can set it to an empty method.
close
Methods and open
methods can also be ignored, which is not used for most drivers.
read
The method should return a string version of the session data that matches the given $sessionid, and no serialization or other coding is required to fetch or store the session data from the drive, because Laravel has already serialized us.
write
Methods should be given $data
to write to the persistent storage system corresponding to $sessionId
, for example, MongoDB, Dynamo and so on.
destroy
Method $sessionId
to remove the corresponding data from the persisted storage.
gc
Method destroys all session data that is greater than a given $lifetime, which can be left blank for systems that own outdated mechanisms, such as Memcached and Redis.
Registration Driver
After the driver is implemented, it needs to be ready to register it to the framework, to add additional drivers to the Laravel session backend, and can use the method on the session façade extend
. We call this method in the service provider's boot
method:
<?phpnamespace App\providers;use App\extensions\mongosessionstore;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 Mongosessionstore; }); /** * Register bindings in the container. * * @return void * /Public Function register () { // }}
Once the session driver is registered, the driver can be used in the configuration file config/session.php
mongo
.
HTTP Layer--session