generate_key(); } // Return existing cookie session if present and valid. if ( isset( $_COOKIE[ self::COOKIE_NAME ] ) ) { $val = sanitize_text_field( wp_unslash( $_COOKIE[ self::COOKIE_NAME ] ) ); if ( $this->is_valid_session_key( $val ) ) { return $val; } } $key = $this->generate_key(); $this->set_cookie( $key, $ttl_seconds ); return $key; } private function generate_key(): string { return bin2hex( random_bytes( 16 ) ); } private function is_valid_session_key( string $key ): bool { return (bool) preg_match( '/^[a-f0-9]{32}$/', $key ); } private function set_cookie( string $key, int $ttl_seconds ): void { if ( headers_sent() || $ttl_seconds <= 0 ) { return; } setcookie( self::COOKIE_NAME, $key, [ 'expires' => time() + $ttl_seconds, 'path' => '/', 'secure' => is_ssl(), 'httponly' => true, 'samesite' => 'Lax', ] ); } }