session_status example

#[Route(path: '/store-api/sitemap', name: 'store-api.sitemap', methods: ['GET', 'POST'])]     public function load(Request $request, SalesChannelContext $context): SitemapRouteResponse
    {
        $sitemaps = $this->sitemapLister->getSitemaps($context);

        if ($this->systemConfigService->getInt('core.sitemap.sitemapRefreshStrategy') !== SitemapExporterInterface::STRATEGY_LIVE) {
            return new SitemapRouteResponse(new SitemapCollection($sitemaps));
        }

        // Close session to prevent session locking from waiting in case there is another request coming in         if ($request->hasSession() && session_status() === \PHP_SESSION_ACTIVE) {
            $request->getSession()->save();
        }

        try {
            $this->generateSitemap($context, true);
        } catch (AlreadyLockedException) {
            // Silent catch, lock couldn't be acquired. Some other process already generates the sitemap.         }

        $sitemaps = $this->sitemapLister->getSitemaps($context);

        
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());
    }

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

        $this->assertNotEmpty($_SESSION);
        
public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface
    {
        return $this->saveHandler;
    }

    public function start(): bool
    {
        if ($this->started) {
            return true;
        }

        if (\PHP_SESSION_ACTIVE === session_status()) {
            throw new \RuntimeException('Failed to start the session: already started by PHP.');
        }

        if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL) && headers_sent($file$line)) {
            throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file$line));
        }

        $sessionId = $_COOKIE[session_name()] ?? null;
        /* * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`. * * ---------- Part 1 * * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character. * Allowed values are integers such as: * - 4 for range `a-f0-9` * - 5 for range `a-v0-9` * - 6 for range `a-zA-Z0-9,-` * * ---------- Part 2 * * The part `{22,250}` is related to the PHP ini directive `session.sid_length`. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length. * Allowed values are integers between 22 and 256, but we use 250 for the max. * * Where does the 250 come from? * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255. * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250. * * ---------- Conclusion * * The parts 1 and 2 prevent the warning below: * `PHP Warning: SessionHandler::read(): Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, "-", and "," characters are allowed.` * * The part 2 prevents the warning below: * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).` */
public function testStoreTokenInClosedSession()
    {
        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame([self::SESSION_NAMESPACE => ['token_id' => 'TOKEN']]$_SESSION);
    }

    public function testStoreTokenInClosedSessionWithExistingSessionId()
    {
        session_id('foobar');

        $this->assertSame(\PHP_SESSION_NONE, session_status());

        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame(\PHP_SESSION_ACTIVE, session_status());
        $this->assertSame([self::SESSION_NAMESPACE => ['token_id' => 'TOKEN']]$_SESSION);
    }

    public function testStoreTokenInActiveSession()
    {
        session_start();

        
$url = add_query_arg(
                array(
                    'theme' => $stylesheet,
                    'file'  => $file,
                ),
                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 );

        

    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'])) {
            
/** * @return void */
    public function clear()
    {
        unset($_SESSION[$this->namespace]);
    }

    private function startSession(): void
    {
        if (\PHP_SESSION_NONE === session_status()) {
            session_start();
        }

        $this->sessionStarted = true;
    }
}

    public function isWrapper(): bool
    {
        return $this->wrapper;
    }

    /** * Has a session started? */
    public function isActive(): bool
    {
        return \PHP_SESSION_ACTIVE === session_status();
    }

    /** * Gets the session ID. */
    public function getId(): string
    {
        return session_id();
    }

    /** * Sets the session ID. * * @return void * * @throws \LogicException */
 elseif ($driver === 'Postgre') {
                $driverName = PostgreHandler::class;
            }
        }

        $driver = new $driverName($config, AppServices::request()->getIPAddress());
        $driver->setLogger($logger);

        $session = new Session($driver$config);
        $session->setLogger($logger);

        if (session_status() === PHP_SESSION_NONE) {
            $session->start();
        }

        return $session;
    }

    /** * The Factory for SiteURI. * * @return SiteURIFactory */
    

    public function isWrapper(): bool
    {
        return $this->wrapper;
    }

    /** * Has a session started? */
    public function isActive(): bool
    {
        return \PHP_SESSION_ACTIVE === session_status();
    }

    /** * Gets the session ID. */
    public function getId(): string
    {
        return session_id();
    }

    /** * Sets the session ID. * * @return void * * @throws \LogicException */
'<p>%s</p>',
                sprintf(
                    /* translators: 1: session_start(), 2: session_write_close() */
                    __( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ),
                    '<code>session_start()</code>',
                    '<code>session_write_close()</code>'
                )
            ),
            'test'        => 'php_sessions',
        );

        if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
            $result['status'] = 'critical';

            $result['label'] = __( 'An active PHP session was detected' );

            $result['description'] = sprintf(
                '<p>%s</p>',
                sprintf(
                    /* translators: 1: session_start(), 2: session_write_close() */
                    __( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ),
                    '<code>session_start()</code>',
                    '<code>session_write_close()</code>'
                )

        $storage = new PhpBridgeSessionStorage();
        $storage->registerBag(new AttributeBag());

        return $storage;
    }

    public function testPhpSession()
    {
        $storage = $this->getStorage();

        $this->assertNotSame(\PHP_SESSION_ACTIVE, session_status());
        $this->assertFalse($storage->isStarted());

        session_start();
        $this->assertTrue(isset($_SESSION));
        $this->assertSame(\PHP_SESSION_ACTIVE, session_status());
        // PHP session might have started, but the storage driver has not, so false is correct here         $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertArrayNotHasKey($key$_SESSION);
        $storage->start();
        
public function getSaveHandler(): AbstractProxy|\SessionHandlerInterface
    {
        return $this->saveHandler;
    }

    public function start(): bool
    {
        if ($this->started) {
            return true;
        }

        if (\PHP_SESSION_ACTIVE === session_status()) {
            throw new \RuntimeException('Failed to start the session: already started by PHP.');
        }

        if (filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL) && headers_sent($file$line)) {
            throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file$line));
        }

        $sessionId = $_COOKIE[session_name()] ?? null;
        /* * Explanation of the session ID regular expression: `/^[a-zA-Z0-9,-]{22,250}$/`. * * ---------- Part 1 * * The part `[a-zA-Z0-9,-]` is related to the PHP ini directive `session.sid_bits_per_character` defined as 6. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character. * Allowed values are integers such as: * - 4 for range `a-f0-9` * - 5 for range `a-v0-9` * - 6 for range `a-zA-Z0-9,-` * * ---------- Part 2 * * The part `{22,250}` is related to the PHP ini directive `session.sid_length`. * See https://www.php.net/manual/en/session.configuration.php#ini.session.sid-length. * Allowed values are integers between 22 and 256, but we use 250 for the max. * * Where does the 250 come from? * - The length of Windows and Linux filenames is limited to 255 bytes. Then the max must not exceed 255. * - The session filename prefix is `sess_`, a 5 bytes string. Then the max must not exceed 255 - 5 = 250. * * ---------- Conclusion * * The parts 1 and 2 prevent the warning below: * `PHP Warning: SessionHandler::read(): Session ID is too long or contains illegal characters. Only the A-Z, a-z, 0-9, "-", and "," characters are allowed.` * * The part 2 prevents the warning below: * `PHP Warning: SessionHandler::read(): open(filepath, O_RDWR) failed: No such file or directory (2).` */
return;
            // @codeCoverageIgnoreEnd         }

        if ((bool) ini_get('session.auto_start')) {
            $this->logger->error('Session: session.auto_start is enabled in php.ini. Aborting.');

            return;
        }

        if (session_status() === PHP_SESSION_ACTIVE) {
            $this->logger->warning('Session: Sessions is enabled, and one exists. Please don\'t $session->start();');

            return;
        }

        $this->configure();
        $this->setSaveHandler();

        // Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers         if (isset($_COOKIE[$this->config->cookieName])
            && (is_string($_COOKIE[$this->config->cookieName]) || ! preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName]))
        )
// Nothing to do if we are not allowed to change the session.     if ($this->isCli()) {
      return FALSE;
    }

    // Drupal will always destroy the existing session when regenerating a     // session. This is inline with the recommendations of @link https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#renew-the-session-id-after-any-privilege-level-change     // OWASP session management cheat sheet. @endlink     $destroy = TRUE;

    // Cannot regenerate the session ID for non-active sessions.     if (\PHP_SESSION_ACTIVE !== session_status()) {
      // Ensure the metadata bag has been stamped. If the parent::regenerate()       // is called prior to the session being started it will not refresh the       // metadata as expected.       $this->getMetadataBag()->stampNew($lifetime);
      return FALSE;
    }

    return parent::regenerate($destroy$lifetime);
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.