LoginSignup
1
1

More than 1 year has passed since last update.

PHPでCookieにSameSite属性を付ける方法

Posted at

PHP7.2以前のsetcookie関数にはSameSite属性をつけるための引数がない!

header関数で生のSet-Cookieヘッダを書くのも手ですが・・・

裏技として、Path属性用の引数を利用してSameSite属性をつけることができます。

7.2以前の方法(裏技)
/* 関数のインターフェース
setcookie(
    string $name,
    string $value = "",
    int $expires = 0,
    string $path = "",
    string $domain = "",
    bool $secure = false,
    bool $httponly = false
): bool
*/

# pathにわたす文字列内に`;`をいれることで、無理やりSameSite属性を指定する!!!
setcookie('cookie_name', 'cookie_value', 0, '/; SameSite=strict', '', true, true);

# 出力されるレスポンスヘッダ
# Set-Cookie: cookie_name=cookie_value; path=/; SameSite=strict; secure; HttpOnly
7.3以降の方法(正規)
# PHP 7.3.0 以降で使える代替のシグネチャ:
# setcookie(string $name, string $value = "", array $options = []): bool

setcookie('cookie_name', 'cookie_value', [
  'expires' => 0,
  'path' => '/',
  'samesite' => 'strict',
  'secure' => true,
  'httponly' => true,
]);

# 出力されるレスポンスヘッダ
# Set-Cookie: cookie_name=cookie_value; path=/; secure; HttpOnly; SameSite=strict

逆に7.3以降でPath属性を使ってSameSiteをねじ込もうとすると以下のエラーになるので注意!!!

Uncaught ValueError: setcookie(): "path" option cannot contain ",", ";", " ", "\t", "\r", "\n", "\013", or "\014"
1
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
1
1