1
0

CookieHelper.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Http;
  8. class CookieHelper {
  9. public const SAMESITE_NONE = 0;
  10. public const SAMESITE_LAX = 1;
  11. public const SAMESITE_STRICT = 2;
  12. public static function setCookie(string $name,
  13. string $value = '',
  14. int $maxAge = 0,
  15. string $path = '',
  16. string $domain = '',
  17. bool $secure = false,
  18. bool $httponly = false,
  19. int $samesite = self::SAMESITE_NONE) {
  20. $header = sprintf(
  21. 'Set-Cookie: %s=%s',
  22. $name,
  23. rawurlencode($value)
  24. );
  25. if ($path !== '') {
  26. $header .= sprintf('; Path=%s', $path);
  27. }
  28. if ($domain !== '') {
  29. $header .= sprintf('; Domain=%s', $domain);
  30. }
  31. if ($maxAge > 0) {
  32. $header .= sprintf('; Max-Age=%d', $maxAge);
  33. }
  34. if ($secure) {
  35. $header .= '; Secure';
  36. }
  37. if ($httponly) {
  38. $header .= '; HttpOnly';
  39. }
  40. if ($samesite === self::SAMESITE_LAX) {
  41. $header .= '; SameSite=Lax';
  42. } elseif ($samesite === self::SAMESITE_STRICT) {
  43. $header .= '; SameSite=Strict';
  44. }
  45. header($header, false);
  46. }
  47. }