CookieHelper.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018, Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Marco Ziech <marco@ziech.net>
  8. * @author Roeland Jago Douma <roeland@famdouma.nl>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OC\Http;
  27. class CookieHelper {
  28. public const SAMESITE_NONE = 0;
  29. public const SAMESITE_LAX = 1;
  30. public const SAMESITE_STRICT = 2;
  31. public static function setCookie(string $name,
  32. string $value = '',
  33. int $maxAge = 0,
  34. string $path = '',
  35. string $domain = '',
  36. bool $secure = false,
  37. bool $httponly = false,
  38. int $samesite = self::SAMESITE_NONE) {
  39. $header = sprintf(
  40. 'Set-Cookie: %s=%s',
  41. $name,
  42. rawurlencode($value)
  43. );
  44. if ($path !== '') {
  45. $header .= sprintf('; Path=%s', $path);
  46. }
  47. if ($domain !== '') {
  48. $header .= sprintf('; Domain=%s', $domain);
  49. }
  50. if ($maxAge > 0) {
  51. $header .= sprintf('; Max-Age=%d', $maxAge);
  52. }
  53. if ($secure) {
  54. $header .= '; Secure';
  55. }
  56. if ($httponly) {
  57. $header .= '; HttpOnly';
  58. }
  59. if ($samesite === self::SAMESITE_LAX) {
  60. $header .= '; SameSite=Lax';
  61. } elseif ($samesite === self::SAMESITE_STRICT) {
  62. $header .= '; SameSite=Strict';
  63. }
  64. header($header, false);
  65. }
  66. }