Session
- Driver Prerequisites
- Database
- Redis
- Use SessionGlobal auxiliary function Session
- Get all Session data
- Determine whether the Session exists A certain value
- Storing data
- Save data in the Session array
- Retrieve & delete a piece of data
- Flash data
- Add custom Session driver
- Implement driver
- Register driver
HTTP session mechanism
Introduction
Since HTTP-driven applications are stateless, Session provides a A way to store information about the user across multiple requests, Laravel handles various built-in backend drivers through the same readable API. Supports popular databases such as Memcached, Redis and others.
##ConfigurationSession’s configuration file is stored in theconfig/session.php
Sessionfile . Be sure to review the options available to you in this file. By default, Laravel configures the Session driver for most applications as
file. In a production environment, you can consider using the
memcachedor
redisdriver to make Session performance even better. The configuration of
driver
presets the location where Session data is stored for each request. Laravel comes with several nice and ready-to-use drivers:
- file
- Store Session in
storage/framework/sessionsmiddle.
- cookie
- Sessions are stored in secure, encrypted cookies.
- database
- Sessions are stored in a relational database.
- memcached
/
redis- Sessions are stored in a cache-based storage system.
- array
- Sessions are stored in PHP arrays but are not persisted.
{tip} Array drivers are generally used for testing and to prevent data stored in the Session from being persisted.
Driver PrerequisitesDatabase When usingdatabase
as the Session driver, you need to create a table containing various Session data. The following is an example of using
Schemato create a 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 the Artisan commandsession:table
to generate this migration:
php artisan session:table php artisan migrate
Redis
Before using Redis as the session driver for Laravel, you need to install the
predis/predis
extension package (~1.0) through Composer. Then configure the Redis connection information in thedatabase
configuration file. In thesession
configuration file, theconnection
option can be used to specify which Redis connection the Session uses.Use Session
## Getting dataThere are two main ways to handle Session data in Laravel: global helper functionssession
and through a
Requestinstance. First, let's look at accessing the session via a controller method type hint for a
Requestinstance. Controller method dependencies will be automatically injected through the Laravel service container:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class UserController extends Controller{ /** * 展示给定用户的配置文件。 * * @param Request $request * @param int $id * @return Response */ public function show(Request $request, $id) { $value = $request->session()->get('key'); // } }
When you get the value from the Session, you can also pass a default value as the second parameter of theget
method . If the specified key does not exist in the Session, this default value will be returned. If a closure is passed as the default value to the
getmethod, and the requested key does not exist, the
getmethod will execute the closure and return its result:
$value = $request->session()->get('key', 'default'); $value = $request->session()->get('key', function () { return 'default'; });
Global auxiliary function SessionYou can also use the global PHP auxiliary functionsession
to obtain and store Session data. When the helper function
sessionis called with a single string value as a parameter, it returns the value of the Session key corresponding to that string. When calling the helper function
sessionwith an array of key-value pairs as parameters, the incoming key values will be stored in the Session:
Route::get('home', function () { // 获取 session 中的一条数据... $value = session('key'); // 指定一个默认值... $value = session('key', 'default'); // 在 Session 中存储一条数据... session(['key' => 'value']); });
{tip} Request instance via HTTP There is no substantial difference between operating Session and using global helper functions
Get all Session dataIf you want to get all Session data, you can use thesession
. Both methods can be tested via the
assertSessionHasmethod available in all test cases.
all
method:
$data = $request->session()->all();
Determine whether a certain value exists in the SessionTo determine whether a certain value exists in the Session, you can use thehas
method. If the value exists and is not
null, then the
hasmethod will return
true:
if ($request->session()->has('users')) { // }
To determine whether a certain value exists in the Session , theexists
method can be used even if its value is
null. The
existsmethod returns
trueif the value exists:
if ($request->session()->exists('users')) { // }
Storing data
To store data into Session, you can use the
put
method, or use the auxiliary functionsession
.// 通过请求实例... $request->session()->put('key', 'value'); // 通过全局辅助函数... session(['key' => 'value']);
Save data in Session array
push
method can add a new value to the Session array. For example, assuming the keyuser.teams
is an array containing team names, you can add a new value to the array like this:$request->session()->push('user.teams', 'developers');
Retrieve & Delete A data
pull
method can retrieve and delete a statement from the Session using only one statement:$value = $request->session()->pull('key', 'default');
Flash data
Sometimes you may want to save data in the Session for the next request, then you can use the
flash
method. Data saved in the Session using this method will only be retained until the next HTTP request arrives, and then it will be deleted. Flash data is mainly used for short-term status messages:$request->session()->flash('status', 'Task was successful!');
If you need to use this one-time data in more requests, you can use the
reflash
method, which will save all One-time requests are held until the next request. If you want to save one-time data, you can usekeep
method:$request->session()->reflash(); $request->session()->keep(['username', 'email']);
Delete data
Theforget
method will delete the specified data from the Session. If you want to delete all data from the Session, you can use theflush
method:$request->session()->forget('key'); $request->session()->flush();
Regenerate Session ID
Regenerating session ID is usually to prevent malicious users from using session fixation to attack your application.
If you use the built-in function
LoginController
, Laravel will automatically regenerate the Session ID in authentication. Otherwise, you need to manually regenerate the Session ID using theregenerate
method.$request->session()->regenerate();
Add a custom Session driver
Implementing the driver
Your custom Session driver must implement the
SessionHandlerInterface
interface. This interface contains some simple methods that we need to implement. The following is an example of the general process for MongoDB implementation:<?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) {} }
{tip} Laravel does not come with a directory for package extensions by default. You can place it in the directory you like. In the above example, we created an
Extensions
directory to storeMongoSessionHandler
.Since the above methods are not very easy to understand, let’s quickly go through each method:
open
Methods usually For file-based Session storage systems. Because Laravel already comes with afile
Session driver. So you don't need to put any code in this method. PHP requires an implementation of this method (this is just a bad interface design), you just need to leave this method empty. Theclose
method is similar to theopen
method and can usually be ignored. For most drivers, this method is not necessary. Theread
method should return the string format of the Session data that matches the given$sessionId
. There is no need to do any serialization or other coding when retrieving or storing session data in your custom driver, because Laravel will automatically perform serialization for you. Thewrite
method writes the given$data
string associated with$sessionId
to some persistent storage system such as MongoDB , Dynamo et al. Again, you don't need to do any serialization or other coding because Laravel handles this for you automatically. Thedestroy
method will delete the data related to$sessionId
from the persistent storage. Thegc
method destroys all data before the given$lifetime
(UNIX timestamp). For systems that have their own expiration mechanism, such as Memcached and Redis, this method can be left blank.
Registering the driver
After implementing the driver, you need to register it in the framework. To add additional drivers to the
Laravel
backend, you need to use theextend
method of theSession
facade. You should call theextend
method in theboot
method in the service provider. You can perform this operation on an existingAppServiceProvider
or create another service provider:<?php namespace App\Providers; use App\Extensions\MongoSessionHandler; use Illuminate\Support\Facades\Session; use Illuminate\Support\ServiceProvider; class SessionServiceProvider extends ServiceProvider{ /** * 执行服务的注册后启动 * * @return void */ public function boot() { Session::extend('mongo', function ($app) { // 返回实现 SessionHandlerInterface 的对象 return new MongoSessionHandler; }); } /** * 在容器中注册绑定关系 * * @return void */ public function register() { // } }
When the driver completes registration, you can use the configuration file
config/session. The
mongodriver is used in php
.This article was first published on the LearnKu.com website.- file