SessionUtils.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Session;
  11. /**
  12. * Session utility functions.
  13. *
  14. * @author Nicolas Grekas <p@tchwork.com>
  15. * @author Rémon van de Kamp <rpkamp@gmail.com>
  16. *
  17. * @internal
  18. */
  19. final class SessionUtils
  20. {
  21. /**
  22. * Finds the session header amongst the headers that are to be sent, removes it, and returns
  23. * it so the caller can process it further.
  24. */
  25. public static function popSessionCookie(string $sessionName, string $sessionId): ?string
  26. {
  27. $sessionCookie = null;
  28. $sessionCookiePrefix = sprintf(' %s=', urlencode($sessionName));
  29. $sessionCookieWithId = sprintf('%s%s;', $sessionCookiePrefix, urlencode($sessionId));
  30. $otherCookies = [];
  31. foreach (headers_list() as $h) {
  32. if (0 !== stripos($h, 'Set-Cookie:')) {
  33. continue;
  34. }
  35. if (11 === strpos($h, $sessionCookiePrefix, 11)) {
  36. $sessionCookie = $h;
  37. if (11 !== strpos($h, $sessionCookieWithId, 11)) {
  38. $otherCookies[] = $h;
  39. }
  40. } else {
  41. $otherCookies[] = $h;
  42. }
  43. }
  44. if (null === $sessionCookie) {
  45. return null;
  46. }
  47. header_remove('Set-Cookie');
  48. foreach ($otherCookies as $h) {
  49. header($h, false);
  50. }
  51. return $sessionCookie;
  52. }
  53. }