setCookie example

private function saveHashInCookie(): void
    {
        $this->cookie = new Cookie(
            $this->rawCookieName,
            $this->hash,
            [
                'expires' => $this->config->expires === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expires,
            ]
        );

        $response = Services::response();
        $response->setCookie($this->cookie);
    }

    /** * CSRF Send Cookie * * @return false|Security * * @deprecated Set cookies to Response object instead. */
    protected function sendCookie(RequestInterface $request)
    {
        
/** * Load the contents of the client session into the data array */
    protected function load(): void
    {
        if (!isset($_SESSION[$this->sessionKey])) {
            return;
        }
        $data = \json_decode($_SESSION[$this->sessionKey], true);
        if (\is_array($data)) {
            foreach ($data as $cookie) {
                $this->setCookie(new SetCookie($cookie));
            }
        } elseif (\strlen($data)) {
            throw new \RuntimeException('Invalid cookie data');
        }
    }
}


            $data = json_decode($loginResponse->getBody()->getContents(), true, 512, \JSON_THROW_ON_ERROR);
            $loginTokenData = [
                'access' => $data['access_token'], 'refresh' => $data['refresh_token'], 'expiry' => $data['expires_in'],
            ];
            $appUrlInfo = parse_url($this->appUrl);
            if (!$appUrlInfo) {
                return $redirect;
            }

            $redirect->headers->setCookie(
                Cookie::create('bearerAuth', json_encode($loginTokenData, \JSON_THROW_ON_ERROR)time() + $data['expires_in']($appUrlInfo['path'] ?? '') . '/admin', $appUrlInfo['host'], null, false)
            );
        } catch (TransferException) {
            // ignore and don't automatically log in         }

        return $redirect;
    }
}
public function testCacheControlClone()
    {
        $headers = ['foo' => 'bar'];
        $bag1 = new ResponseHeaderBag($headers);
        $bag2 = new ResponseHeaderBag($bag1->allPreserveCase());
        $this->assertEquals($bag1->allPreserveCase()$bag2->allPreserveCase());
    }

    public function testToStringIncludesCookieHeaders()
    {
        $bag = new ResponseHeaderBag([]);
        $bag->setCookie(Cookie::create('foo', 'bar'));

        $this->assertSetCookieHeader('foo=bar; path=/; httponly; samesite=lax', $bag);

        $bag->clearCookie('foo');

        $this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d M Y H:i:s T', time() - 31536001).'; Max-Age=0; path=/; httponly', $bag);
    }

    public function testClearCookieSecureNotHttpOnly()
    {
        $bag = new ResponseHeaderBag([]);

        
<?php
use Symfony\Component\HttpFoundation\Cookie;

$r = require __DIR__.'/common.inc';

$r->headers->setCookie(new Cookie('CookieSamesiteLaxTest', 'LaxValue', 0, '/', null, false, true, false, Cookie::SAMESITE_LAX));
$r->sendHeaders();
$this->mink->setDefaultSessionName('default');
    $this->registerSessions();

    $this->initFrontPage();

    // Copies cookies from the current environment, for example, XDEBUG_SESSION     // in order to support Xdebug.     // @see BrowserTestBase::initFrontPage()     $cookies = $this->extractCookiesFromRequest(\Drupal::request());
    foreach ($cookies as $cookie_name => $values) {
      foreach ($values as $value) {
        $session->setCookie($cookie_name$value);
      }
    }

    return $session;
  }

  /** * Visits the front page when initializing Mink. * * According to the W3C WebDriver specification a cookie can only be set if * the cookie domain is equal to the domain of the active document. When the * browser starts up the active document is not our domain but 'about:blank' * or similar. To be able to set our User-Agent and Xdebug cookies at the * start of the test we now do a request to the front page so the active * document matches the domain. * * @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie * @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975 */
public function sAddNote($articleID$articleName$articleOrderNumber)
    {
        $cookieData = $this->front->Request()->getCookie();
        $uniqueId = $this->front->Request()->getCookie('sUniqueID');

        if (!empty($cookieData) && empty($uniqueId)) {
            $basePath = Shopware()->Shop()->getBasePath();
            if ($basePath === null || $basePath === '') {
                $basePath = '/';
            }
            $uniqueId = Random::getAlphanumericString(32);
            $this->front->Response()->headers->setCookie(
                new Cookie(
                    'sUniqueID',
                    $uniqueId,
                    time() + (86400 * 360),
                    $basePath,
                    null,
                    $this->front->Request()->isSecure()
                )
            );
        }

        
$optinService = $this->container->get(\Shopware\Components\OptinServiceInterface::class);

        $data = $optinService->get(OptinServiceInterface::TYPE_THEME_PREVIEW, $hash);

        if (!$data) {
            return false;
        }

        $optinService->delete(OptinServiceInterface::TYPE_THEME_PREVIEW, $hash);

        $this->Response()->headers->setCookie(
            new Cookie(
                $data['sessionName'],
                $data['sessionValue'],
                0,
                $this->Request()->getBaseUrl(),
                null,
                $this->Request()->isSecure()
            )
        );

        // Disable http cache for this Request
$removePath = $request->getBasePath() . '/shopware.php';
            $newPath = str_replace($removePath$request->getBasePath()$request->getRequestUri());
            $newPath = preg_replace('/\/{2,}/', '/', $newPath);
        }

        if (isset($newPath)) {
            // reset the cookie so only one valid cookie will be set IE11 fix             $basePath = $shop->getBasePath();
            if ($basePath === null || $basePath === '') {
                $basePath = '/';
            }
            $response->headers->setCookie(new Cookie('session-' . $shop->getId(), '', 1, $basePath));
            $response->setRedirect($newPath, 301);
        } else {
            $this->upgradeShop($request$response);
            $this->initServiceMode($request);
        }

        $this->get(ContextServiceInterface::class)->initializeShopContext();
    }

    public function getCapabilities()
    {
        


        // wait for the lock to be released         if ($this->waitForLock($request)) {
            // replace the current entry with the fresh one             $new = $this->lookup($request);
            $entry->headers = $new->headers;
            $entry->setContent($new->getContent());
            $entry->setStatusCode($new->getStatusCode());
            $entry->setProtocolVersion($new->getProtocolVersion());
            foreach ($new->headers->getCookies() as $cookie) {
                $entry->headers->setCookie($cookie);
            }
        } else {
            // backend is slow as hell, send a 503 response (to avoid the dog pile effect)             $entry->setStatusCode(503);
            $entry->setContent('503 Service Unavailable');
            $entry->headers->set('Retry-After', 10);
        }

        return true;
    }

    
$json = \file_get_contents($filename);
        if (false === $json) {
            throw new \RuntimeException("Unable to load file {$filename}");
        }
        if ($json === '') {
            return;
        }

        $data = Utils::jsonDecode($json, true);
        if (\is_array($data)) {
            foreach ($data as $cookie) {
                $this->setCookie(new SetCookie($cookie));
            }
        } elseif (\is_scalar($data) && !empty($data)) {
            throw new \RuntimeException("Invalid cookie file: {$filename}");
        }
    }
}

    public function getPluginInformation(Response $response, Request $request)
    {
        if (!$this->isPluginsSubscriptionCookieValid($request)) {
            return false;
        }

        try {
            $cookie = new Cookie('lastCheckSubscriptionDate', date('dmY')time() + 60 * 60 * 24, '/', null, $request->isSecure());
            $response->headers->setCookie($cookie);

            return $this->getPluginInformationFromApi();
        } catch (ShopSecretException $e) {
            $this->exception = $e;
            $this->resetShopSecret();

            return false;
        } catch (Exception $e) {
            $this->exception = $e;

            return false;
        }
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Test\Constraint\ResponseHasCookie;

class ResponseHasCookieTest extends TestCase
{
    public function testConstraint()
    {
        $response = new Response();
        $response->headers->setCookie(Cookie::create('foo', 'bar'));
        $constraint = new ResponseHasCookie('foo');
        $this->assertTrue($constraint->evaluate($response, '', true));
        $constraint = new ResponseHasCookie('bar');
        $this->assertFalse($constraint->evaluate($response, '', true));

        try {
            $constraint->evaluate($response);
        } catch (ExpectationFailedException $e) {
            $this->assertEquals("Failed asserting that the Response has cookie \"bar\".\n", TestFailure::exceptionToString($e));

            return;
        }
$response->headers->removeCookie($cookieName$currentPath);
                $response->headers->removeCookie($cookieName$currentPathWithoutSlash);
                $response->headers->removeCookie($cookieName$request->getBaseUrl());
                $response->headers->removeCookie($cookieName$cookieBasePath . $request->getBaseUrl());
            }
        }

        foreach ($requestCookies as $cookieKey => $cookieName) {
            if (!$validationFunction($cookieKey)) {
                $host = preg_replace('/^www./', '', $request->getHost());
                foreach ([$host, null] as $cookieHost) {
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, '/', $cookieHost));
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, $cookieBasePath$cookieHost));
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, $cookiePath$cookieHost));
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, $currentPath$cookieHost));
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, $currentPathWithoutSlash$cookieHost));
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, $request->getBaseUrl()$cookieHost));
                    $response->headers->setCookie(new Cookie($cookieKey, null, 0, $cookieBasePath . $request->getBaseUrl()$cookieHost));
                }
            }
        }
    }

    
// Set global variables $app->view()->setData('version', $container->offsetGet('shopware.version'));
$app->view()->setData('t', $translationService);
$app->view()->setData('menuHelper', $menuHelper);
$app->view()->setData('selectedLanguage', $selectedLanguage);
$app->view()->setData('translations', $translations);
$app->view()->setData('baseUrl', Utils::getBaseUrl($app));
$app->view()->setData('app', $app);
$app->view()->setData('error', false);
$app->view()->setData('parameters', $_SESSION['parameters']);

$app->setCookie('installed-locale', localeForLanguage($selectedLanguage)time() + 7200, '/');

$app->add(new XssMiddleware());

$app->error(function DException $e) use ($app) {
    if (!$app->request()->isAjax()) {
        throw $e;
    }

    $response = $app->response();
    $data = [
        'code' => $e->getCode(),
        
Home | Imprint | This part of the site doesn't use cookies.