2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelでcookieが取得できない場合の対処法と暗号化の除外に正規表現を使う方法

Last updated at Posted at 2023-09-13

概要

Laravelではブラウザに保存されているcookieはEncryptCookiesというMiddlewareにより暗号化される。
その結果、cookieのバリューにnullが設定されてしまい正しくcookieが取得できない。

.php
dd($request->cookie());

// "test_cookie" => null

対処法

対処法は2つある。

1.PHPのグローバル変数である$_COOKIEを使う

.php
$_COOKIE['test_cookie']

// "test_cookie" => 12345

PHPのグローバル変数である$_COOKIEを使えば取得できるが、Laravelのシステムでは、Laravelのお作法に則った方がよいため、こちらは最終手段にしたほうが良い。

2.EncryptCookiesの$exceptで暗号化の対象から除外したいcookieを設定する

EncryptCookiesでは暗号化の対象から除外するcookieのキーを設定できるため、これを使うのが正攻法だろう。
方法は下記の様に$exceptプロパティに暗号化の対象から除外したいcookieのキーを設定するだけで良い。

app\Http\Middleware\EncryptCookies.php

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        'test_cookie'
    ];

cookieのキーを正規表現で設定したい

例えば、test_から始まるcookieだけ暗号化の対象から除外したい場合はどうしたらよいだろうか?

方法としては、

1.EncryptCookieshandleメソッドをオーバーロードする
2.暗号化前のcookieをすべて取得する
3.cookieのnullを除去する
4.array_flip()でキーとバリューを入れ替える
5.preg_grep()test_から始まるcookieを取得する
6.array_keys()キーだけを取得し$this->exceptに追加する

app\Http\Middleware\EncryptCookies.php

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle($request, Closure $next)
    {
        $cookies = $request->cookie();
        $cookies = array_filter($cookies, function($value) { return $value !== null; });
        $cookies = array_flip($cookies);
        $cookie = preg_grep('/^test_/',$cookies);
        $this->except = array_keys(array_flip($cookie));

        return $this->encrypt($next($this->decrypt($request)));
    }

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?