session_write_close example


        $themeId = $this->Request()->getParam('themeId');
        $shopId = $this->Request()->getParam('shopId');

        $theme = $this->getRepository()->find($themeId);
        if (!$theme instanceof Template) {
            throw new ModelNotFoundException(Template::class$themeId);
        }

        $shop = $this->getManager()->getRepository(Shop::class)->getActiveById($shopId);

        session_write_close();

        $this->get(ShopRegistrationServiceInterface::class)->registerShop($shop);

        $session = $this->get('session');

        $session->template = $theme->getTemplate();
        $session->Admin = true;

        if (!$this->Request()->isXmlHttpRequest()) {
            $this->get('events')->notify('Shopware_Theme_Preview_Starts', [
                'session' => Shopware()->Session(),
                
// Register error handler to add information about the current save handler         $previousHandler = set_error_handler(function D$type$msg$file$line) use (&$previousHandler) {
            if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
                $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
                $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
            }

            return $previousHandler ? $previousHandler($type$msg$file$line) : false;
        });

        try {
            session_write_close();
        } finally {
            restore_error_handler();

            // Restore only if not empty             if ($_SESSION) {
                $_SESSION = $session;
            }
        }

        $this->closed = true;
        $this->started = false;
    }
protected function setUp(): void
    {
        $this->iniSet('session.save_handler', 'files');
        $this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sftest');
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath);
        }
    }

    protected function tearDown(): void
    {
        session_write_close();
        array_map('unlink', glob($this->savePath.'/*'));
        if (is_dir($this->savePath)) {
            @rmdir($this->savePath);
        }
    }

    protected function getStorage(array $options = []): NativeSessionStorage
    {
        $storage = new NativeSessionStorage($options);
        $storage->registerBag(new AttributeBag());

        
admin_url( 'theme-editor.php' )
            );
        } else {
            $url = admin_url();
        }

        if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
            /* * Close any active session to prevent HTTP requests from timing out * when attempting to connect back to the site. */
            session_write_close();
        }

        $url                    = add_query_arg( $scrape_params$url );
        $r                      = wp_remote_get( $urlcompact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
        $body                   = wp_remote_retrieve_body( $r );
        $scrape_result_position = strpos( $body$needle_start );

        $loopback_request_failure = array(
            'code'    => 'loopback_request_failed',
            'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ),
        );
        
/** * Writes session data and close the current session. * * @return void */
    public function close()
    {
        if (ENVIRONMENT === 'testing') {
            return;
        }

        session_write_close();
    }

    /** * Sets user data into the session. * * If $data is a string, then it is interpreted as a session property * key, and $value is expected to be non-null. * * If $data is an array, it is expected to be an array of key/value pairs * to be set as session properties. * * @param array|string $data Property name or associative array of properties * @param array|bool|float|int|object|string|null $value Property value if single key provided */


        if (empty($user['email'])) {
            return;
        }

        $shop = $this->getShopRepository()->getActiveById($user['language']);
        if ($shop === null) {
            return;
        }

        session_write_close();

        $this->get(ShopRegistrationServiceInterface::class)->registerShop($shop);

        $session = $this->get('session');
        $session->clear();
        $session->migrate(true);

        Shopware()->Session()->offsetSet('sessionId', $session->getId());
        Shopware()->Container()->set('sessionid', $session->getId());

        Shopware()->Session()->set('Admin', true);
        
// Register error handler to add information about the current save handler         $previousHandler = set_error_handler(function D$type$msg$file$line) use (&$previousHandler) {
            if (\E_WARNING === $type && str_starts_with($msg, 'session_write_close():')) {
                $handler = $this->saveHandler instanceof SessionHandlerProxy ? $this->saveHandler->getHandler() : $this->saveHandler;
                $msg = sprintf('session_write_close(): Failed to write session data with "%s" handler', $handler::class);
            }

            return $previousHandler ? $previousHandler($type$msg$file$line) : false;
        });

        try {
            session_write_close();
        } finally {
            restore_error_handler();

            // Restore only if not empty             if ($_SESSION) {
                $_SESSION = $session;
            }
        }

        $this->closed = true;
        $this->started = false;
    }

    public function onInitResourceBackendSession(Enlight_Event_EventArgs $args)
    {
        // If another session is already started, save and close it before starting the backend session below.         // We need to do this, because the other session would use the session id of the backend session and thus write         // its data into the wrong session.         Enlight_Components_Session_Namespace::ensureFrontendSessionClosed(Shopware()->Container());
        // Ensure no session is active before starting the backend session below. We need to do this because there could         // be another session with inconsistent/invalid state in the container.         if (session_status() === PHP_SESSION_ACTIVE) {
            session_write_close();
            // The empty session id signals to `Enlight_Components_Session_Namespace::start()` that the session cookie             // should be used as session id.             session_id('');
        }

        $sessionOptions = $this->getSessionOptions();
        $saveHandler = $this->createSaveHandler(Shopware()->Container());
        $storage = new NativeSessionStorage($sessionOptions);

        if (!empty($sessionOptions['unitTestEnabled'])) {
            $storage = new MockArraySessionStorage();
        }
protected function setUp(): void
    {
        $this->iniSet('session.save_handler', 'files');
        $this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sftest');
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath);
        }
    }

    protected function tearDown(): void
    {
        session_write_close();
        array_map('unlink', glob($this->savePath.'/*'));
        if (is_dir($this->savePath)) {
            @rmdir($this->savePath);
        }
    }

    protected function getStorage(): PhpBridgeSessionStorage
    {
        $storage = new PhpBridgeSessionStorage();
        $storage->registerBag(new AttributeBag());

        

    public function createSession(Container $container, ?SessionHandlerInterface $saveHandler = null)
    {
        // If another session is already started, save and close it before starting the frontend session below.         // We need to do this, because the other session would use the session id of the frontend session and thus write         // its data into the wrong session.         Enlight_Components_Session_Namespace::ensureBackendSessionClosed($container);
        // Ensure no session is active before starting the frontend session below. We need to do this because there         // could be another session with inconsistent/invalid state in the container.         if (session_status() === PHP_SESSION_ACTIVE) {
            session_write_close();
            // The empty session id signals to `Enlight_Components_Session_Namespace::start()` that the session cookie             // should be used as session id.             session_id('');
        }

        $sessionOptions = $container->getParameter('shopware.session');

        if (!\is_array($sessionOptions)) {
            throw new RuntimeException('Parameter shopware.session has to be an array');
        }

        
public function indexAction(): void
    {
        $sitemaps = $this->sitemapLister->getSitemaps($this->get('shop')->getId());

        $lastGenerated = (int) $this->config->get('sitemapLastRefresh');
        $refreshInterval = (int) $this->config->get('sitemapRefreshTime');

        // If there are no sitemaps yet (or they are too old) and the generation strategy is "live", generate sitemaps         if ((empty($sitemaps) || time() > $refreshInterval + $lastGenerated)
            && $this->config->get('sitemapRefreshStrategy') === SitemapExporterInterface::STRATEGY_LIVE) {
            // Close session to prevent session locking from waiting in case there is another request coming in             session_write_close();

            try {
                $this->sitemapExporter->generate($this->get('shop'));
            } catch (AlreadyLockedException $exception) {
                // Silent catch, lock couldn't be acquired. Some other process already generates the sitemap.             }

            $sitemaps = $this->sitemapLister->getSitemaps($this->get('shop')->getId());
        }

        $this->Response()->headers->set('content-type', 'text/xml; charset=utf-8');
        
<?php
require __DIR__.'/common.inc';

setcookie('abc', 'def');

session_set_save_handler(new TestSessionHandler('abc|i:123;'), false);
session_start();
session_write_close();
session_start();

$_SESSION['abc'] = 234;
unset($_SESSION['abc']);
new SessionListener($container, true))->onSessionUsage();
    }

    /** * @runInSeparateProcess */
    public function testReset()
    {
        session_start();
        $_SESSION['test'] = ['test'];
        session_write_close();

        $this->assertNotEmpty($_SESSION);
        $this->assertNotEmpty(session_id());

        $container = new Container();

        (new SessionListener($container, true))->reset();

        $this->assertEmpty($_SESSION);
        $this->assertEmpty(session_id());
        $this->assertSame(\PHP_SESSION_NONE, session_status());
    }
Home | Imprint | This part of the site doesn't use cookies.