A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.yiiframework.com/doc/api/2.0/yii-web-session below:

Session, yii\web\Session | API Documentation for Yii 2.0

Session provides session data management and the related configurations.

Session is a Web application component that can be accessed via Yii::$app->session.

To start the session, call open(); To complete and send out session data, call close(); To destroy the session, call destroy().

Session can be used like an array to set and get session data. For example,

$session = new Session;
$session->open();
$value1 = $session['name1'];  
$value2 = $session['name2'];  
foreach ($session as $name => $value) 
$session['name3'] = $value3;  

Session can be extended to support customized session storage. To do so, override $useCustomStorage so that it returns true, and override these methods with the actual logic about using custom storage: openSession(), closeSession(), readSession(), writeSession(), destroySession() and gcSession().

Session also supports a special type of session data, called flash messages. A flash message is available only in the current request and the next request. After that, it will be deleted automatically. Flash messages are particularly useful for displaying confirmation messages. To use flash messages, simply call methods such as setFlash(), getFlash().

For more details and usage information on Session, see the guide article on sessions.

Hide inherited properties

Holds the session id in case useStrictMode is enabled and the session id needs to be regenerated

Holds the original session module (before a custom handler is registered) so that it can be restored when a Session component without custom handler is used after one that has.

Flash messages (key => message or key => [message1, message2]).

The session cookie parameters.

The number of session variables.

The key identifying the flash message. Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, its value will be overwritten by this method.

The name of the session variable that stores the flash message data.

The probability (percentage) that the GC (garbage collection) process is started on every session initialization.

An object implementing the SessionHandlerInterface or a configuration array. If set, will be used to provide persistency instead of build-in methods.

Whether the current request has sent the session ID.

Whether the session has started.

An iterator for traversing the session variables.

The current session name.

The current session save path, defaults to '/tmp'.

The number of seconds after which data will be seen as 'garbage' and cleaned up. The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).

The value indicating whether cookies should be used to store session IDs.

Whether to use custom storage.

Whether strict mode is enabled or not.

Whether transparent sid support is enabled or not, defaults to false.

Hide inherited methods

Defined in: yii\base\Component::__call()

Calls the named method which is not a class method.

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

Source code

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            

Defined in: yii\base\Component::__clone()

This method is called after the object is created by cloning an existing one.

It removes all behaviors because they are attached to the old object.

Source code

                public function __clone()
{
    $this->_events = [];
    $this->_eventWildcards = [];
    $this->_behaviors = null;
}

            

Defined in: yii\base\BaseObject::__construct()

Constructor.

The default implementation does two things:

If this method is overridden in a child class, it is recommended that

public void __construct ( $config = [] ) $config array

Name-value pairs that will be used to initialize the object properties

Source code

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            

Defined in: yii\base\Component::__get()

Returns the value of a component property.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

See also __set().

Source code

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        
        return $this->$getter();
    }
    
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            

Defined in: yii\base\Component::__isset()

Checks if a property is set, i.e. defined and not null.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

See also https://www.php.net/manual/en/function.isset.php.

Source code

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            

Defined in: yii\base\Component::__set()

Sets the value of a component property.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

See also __get().

Source code

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        
        $name = trim(substr($name, 3));
        if ($value instanceof Behavior) {
            $this->attachBehavior($name, $value);
        } elseif ($value instanceof \Closure) {
            $this->attachBehavior($name, call_user_func($value));
        } elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) {
            $this->attachBehavior($name, Yii::createObject($value));
        } elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) {
            $this->attachBehavior($name, Yii::createObject($value));
        } elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) {
            $this->attachBehavior($name, Yii::createObject($value));
        } else {
            throw new InvalidConfigException('Class is not of type ' . Behavior::class . ' or its subclasses');
        }
        return;
    }
    
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            

Defined in: yii\base\Component::__unset()

Sets a component property to be null.

This method will check in the following order and act accordingly:

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property).

See also https://www.php.net/manual/en/function.unset.php.

Source code

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            

Adds a flash message.

If there are existing flash messages with the same key, the new one will be appended to the existing message array.

See also:

public void addFlash ( $key, $value true, $removeAfterAccess true ) $key string

The key identifying the flash message.

$value mixed

Flash message

$removeAfterAccess boolean

Whether the flash message should be automatically removed only if it is accessed. If false, the flash message will be automatically removed after the next request, regardless if it is accessed or not. If true (default value), the flash message will remain until after it is accessed.

Source code

                public function addFlash($key, $value = true, $removeAfterAccess = true)
{
    $counters = $this->get($this->flashParam, []);
    $counters[$key] = $removeAfterAccess ? -1 : 0;
    $_SESSION[$this->flashParam] = $counters;
    if (empty($_SESSION[$key])) {
        $_SESSION[$key] = [$value];
    } elseif (is_array($_SESSION[$key])) {
        $_SESSION[$key][] = $value;
    } else {
        $_SESSION[$key] = [$_SESSION[$key], $value];
    }
}

            

Source code

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
public void attachBehaviors ( $behaviors ) $behaviors array

List of behaviors to be attached to the component

Source code

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            

Defined in: yii\base\Component::behaviors()

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

Source code

                public function behaviors()
{
    return [];
}

            

Defined in: yii\base\Component::canGetProperty()

Returns a value indicating whether a property can be read.

A property can be read if:

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true ) $name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be read

Source code

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            

Defined in: yii\base\Component::canSetProperty()

Returns a value indicating whether a property can be set.

A property can be written if:

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true ) $name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be written

Source code

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            

Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Source code

                public static function className()
{
    return get_called_class();
}

            

Ends the current session and store session data.

Source code

                public function close()
{
    if ($this->getIsActive()) {
        YII_DEBUG ? session_write_close() : @session_write_close();
    }
    $this->_forceRegenerateId = null;
}

            

Returns the number of items in the session.

This method is required by Countable interface.

Source code

                
public function count()
{
    return $this->getCount();
}

            

Frees all session variables and destroys all data registered to a session.

This method has no effect when session is not active. Make sure to call open() before calling it.

See also:

Source code

                public function destroy()
{
    if ($this->getIsActive()) {
        $sessionId = session_id();
        $this->close();
        $this->setId($sessionId);
        $this->open();
        session_unset();
        session_destroy();
        $this->setId($sessionId);
    }
}

            

Source code

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            

Source code

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            

Source code

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            

If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception.

This function saves session data to temporary variable and stop session.

Source code

                protected function freeze()
{
    if ($this->getIsActive()) {
        if (isset($_SESSION)) {
            $this->_frozenSessionData = $_SESSION;
        }
        $this->close();
        Yii::info('Session frozen', __METHOD__);
    }
}

            

Returns the session variable value with the session variable name.

If the session variable does not exist, the $defaultValue will be returned.

public mixed get ( $key, $defaultValue null ) $key string

The session variable name

$defaultValue mixed

The default value to be returned when the session variable does not exist.

return mixed

The session variable value, or $defaultValue if the session variable does not exist.

Source code

                public function get($key, $defaultValue = null)
{
    $this->open();
    return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
}

            

Returns all flash messages.

You may use this method to display all the flash messages in a view file:

<?php
foreach (Yii::$app->session->getAllFlashes() as $key => $message) {
    echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>

With the above code you can use the bootstrap alert classes such as success, info, danger as the flash message key to influence the color of the div.

Note that if you use addFlash(), $message will be an array, and you will have to adjust the above code.

See also:

public array getAllFlashes ( $delete false ) $delete boolean

Whether to delete the flash messages right after this method is called. If false, the flash messages will be automatically deleted in the next request.

return array

Flash messages (key => message or key => [message1, message2]).

Source code

                public function getAllFlashes($delete = false)
{
    $counters = $this->get($this->flashParam, []);
    $flashes = [];
    foreach (array_keys($counters) as $key) {
        if (array_key_exists($key, $_SESSION)) {
            $flashes[$key] = $_SESSION[$key];
            if ($delete) {
                unset($counters[$key], $_SESSION[$key]);
            } elseif ($counters[$key] < 0) {
                
                $counters[$key] = 1;
            }
        } else {
            unset($counters[$key]);
        }
    }
    $_SESSION[$this->flashParam] = $counters;
    return $flashes;
}

            

Source code

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            

Source code

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            

Returns current cache limiter

Source code

                public function getCacheLimiter()
{
    return session_cache_limiter();
}

            

Source code

                public function getCookieParams()
{
    return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}

            

Returns the number of items in the session.

Source code

                public function getCount()
{
    $this->open();
    return count($_SESSION);
}

            
public mixed getFlash ( $key, $defaultValue null, $delete false ) $key string

The key identifying the flash message

$defaultValue mixed

Value to be returned if the flash message does not exist.

$delete boolean

Whether to delete this flash message right after this method is called. If false, the flash message will be automatically deleted in the next request.

return mixed

The flash message or an array of messages if addFlash was used

Source code

                public function getFlash($key, $defaultValue = null, $delete = false)
{
    $counters = $this->get($this->flashParam, []);
    if (isset($counters[$key])) {
        $value = $this->get($key, $defaultValue);
        if ($delete) {
            $this->removeFlash($key);
        } elseif ($counters[$key] < 0) {
            
            $counters[$key] = 1;
            $_SESSION[$this->flashParam] = $counters;
        }
        return $value;
    }
    return $defaultValue;
}

            
public float getGCProbability ( ) return float

The probability (percentage) that the GC (garbage collection) process is started on every session initialization.

Source code

                public function getGCProbability()
{
    return (float) (ini_get('session.gc_probability') / ini_get('session.gc_divisor') * 100);
}

            

Returns a value indicating whether the current request has sent the session ID.

The default implementation will check cookie and $_GET using the session name. If you send session ID via other ways, you may need to override this method or call setHasSessionId() to explicitly set whether the session ID is sent.

Source code

                public function getHasSessionId()
{
    if ($this->_hasSessionId === null) {
        $name = $this->getName();
        $request = Yii::$app->getRequest();
        if (!empty($_COOKIE[$name]) && ini_get('session.use_cookies')) {
            $this->_hasSessionId = true;
        } elseif (!ini_get('session.use_only_cookies') && ini_get('session.use_trans_sid')) {
            $this->_hasSessionId = $request->get($name) != '';
        } else {
            $this->_hasSessionId = false;
        }
    }
    return $this->_hasSessionId;
}

            

Source code

                public function getId()
{
    return session_id();
}

            

Source code

                public function getIsActive()
{
    return session_status() === PHP_SESSION_ACTIVE;
}

            

Returns an iterator for traversing the session variables.

This method is required by the interface IteratorAggregate.

Source code

                
public function getIterator()
{
    $this->open();
    return new SessionIterator();
}

            

Source code

                public function getName()
{
    return session_name();
}

            

Source code

                public function getSavePath()
{
    return session_save_path();
}

            
public integer getTimeout ( ) return integer

The number of seconds after which data will be seen as 'garbage' and cleaned up. The default value is 1440 seconds (or the value of "session.gc_maxlifetime" set in php.ini).

Source code

                public function getTimeout()
{
    return (int) ini_get('session.gc_maxlifetime');
}

            

Returns the value indicating whether cookies should be used to store session IDs.

See also setUseCookies().

Source code

                public function getUseCookies()
{
    if (ini_get('session.use_cookies') === '0') {
        return false;
    } elseif (ini_get('session.use_only_cookies') === '1') {
        return true;
    }
    return null;
}

            

Returns a value indicating whether to use custom session storage.

This method should be overridden to return true by child classes that implement custom session storage. To implement custom session storage, override these methods: openSession(), closeSession(), readSession(), writeSession(), destroySession() and gcSession().

Source code

                public function getUseCustomStorage()
{
    return false;
}

            

Source code

                public function getUseStrictMode()
{
    if (PHP_VERSION_ID < 50502) {
        return self::$_useStrictModePolyfill;
    }
    return (bool)ini_get('session.use_strict_mode');
}

            

Source code

                public function getUseTransparentSessionID()
{
    return ini_get('session.use_trans_sid') == 1;
}

            
public boolean has ( $key ) $key mixed

Session variable name

return boolean

Whether there is the named session variable

Source code

                public function has($key)
{
    $this->open();
    return isset($_SESSION[$key]);
}

            

Source code

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            

Returns a value indicating whether there are flash messages associated with the specified key.

public boolean hasFlash ( $key ) $key string

Key identifying the flash message type

return boolean

Whether any flash messages exist under specified key

Source code

                public function hasFlash($key)
{
    return $this->getFlash($key) !== null;
}

            

Defined in: yii\base\Component::hasMethod()

Returns a value indicating whether a method is defined.

A method is defined if:

public boolean hasMethod ( $name, $checkBehaviors true ) $name string

The property name

$checkBehaviors boolean

Whether to treat behaviors' methods as methods of this component

return boolean

Whether the method is defined

Source code

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            

Defined in: yii\base\Component::hasProperty()

Returns a value indicating whether a property is defined for this component.

A property is defined if:

See also:

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true ) $name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property is defined

Source code

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            

Initializes the application component.

This method is required by IApplicationComponent and is invoked by application.

Source code

                public function init()
{
    parent::init();
    register_shutdown_function([$this, 'close']);
    if ($this->getIsActive()) {
        Yii::warning('Session is already started', __METHOD__);
        $this->updateFlashCounters();
    }
}

            

Defined in: yii\base\Component::off()

Detaches an existing event handler from this component.

This method is the opposite of on().

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

See also on().

public boolean off ( $name, $handler null ) $name string

Event name

$handler callable|null

The event handler to be removed. If it is null, all handlers attached to the named event will be removed.

return boolean

If a handler is found and detached

Source code

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            

This method is required by the interface ArrayAccess.

Source code

                
public function offsetExists($offset)
{
    $this->open();
    return isset($_SESSION[$offset]);
}

            

This method is required by the interface ArrayAccess.

public mixed offsetGet ( $offset ) $offset integer|string

The offset to retrieve element.

return mixed

The element at the offset, null if no element is found at the offset

Source code

                
public function offsetGet($offset)
{
    $this->open();
    return isset($_SESSION[$offset]) ? $_SESSION[$offset] : null;
}

            

This method is required by the interface ArrayAccess.

public void offsetSet ( $offset, $item ) $offset integer|string

The offset to set element

$item mixed

The element value

Source code

                
public function offsetSet($offset, $item)
{
    $this->open();
    $_SESSION[$offset] = $item;
}

            

This method is required by the interface ArrayAccess.

Source code

                
public function offsetUnset($offset)
{
    $this->open();
    unset($_SESSION[$offset]);
}

            

Defined in: yii\base\Component::on()

Attaches an event handler to an event.

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         
[$object, 'handleClick']          
['Page', 'handleClick']           
'handleClick'                     

The event handler must be defined with the following signature,

function ($event)

where $event is an yii\base\Event object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

See also off().

public void on ( $name, $handler, $data null, $append true ) $name string

The event name

$handler callable

The event handler

$data mixed

The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data.

$append boolean

Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

Source code

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            

Starts the session.

Source code

                public function open()
{
    if ($this->getIsActive()) {
        return;
    }
    $this->registerSessionHandler();
    if ($this->getUseCookies() !== false) {
        $this->setCookieParamsInternal();
    }
    YII_DEBUG ? session_start() : @session_start();
    if ($this->getUseStrictMode() && $this->_forceRegenerateId) {
        $this->regenerateID();
        $this->_forceRegenerateId = null;
    }
    if ($this->getIsActive()) {
        Yii::info('Session started', __METHOD__);
        $this->updateFlashCounters();
    } else {
        $error = error_get_last();
        $message = isset($error['message']) ? $error['message'] : 'Failed to start session.';
        Yii::error($message, __METHOD__);
    }
}

            
public void regenerateID ( $deleteOldSession false ) $deleteOldSession boolean

Whether to delete the old associated session file or not.

Source code

                public function regenerateID($deleteOldSession = false)
{
    if ($this->getIsActive()) {
        
        
        if (YII_DEBUG && !headers_sent()) {
            session_regenerate_id($deleteOldSession);
        } else {
            @session_regenerate_id($deleteOldSession);
        }
    }
}

            

Registers session handler.

Source code

                protected function registerSessionHandler()
{
    $sessionModuleName = session_module_name();
    if (static::$_originalSessionModule === null) {
        static::$_originalSessionModule = $sessionModuleName;
    }
    if ($this->handler === null && $this->getUseCustomStorage()) {
        $this->handler = Yii::createObject(
            [
                '__class' => SessionHandler::class,
                '__construct()' => [$this],
            ]
        );
    }
    if ($this->handler !== null) {
        if (is_array($this->handler)) {
            $this->handler = Yii::createObject($this->handler);
        }
        if (!$this->handler instanceof \SessionHandlerInterface) {
            throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the SessionHandlerInterface.');
        }
        YII_DEBUG ? session_set_save_handler($this->handler, false) : @session_set_save_handler($this->handler, false);
    } elseif (
        $sessionModuleName !== static::$_originalSessionModule
        && static::$_originalSessionModule !== null
        && static::$_originalSessionModule !== 'user'
    ) {
        session_module_name(static::$_originalSessionModule);
    }
}

            

Removes a session variable.

public mixed remove ( $key ) $key string

The name of the session variable to be removed

return mixed

The removed value, null if no such session variable.

Source code

                public function remove($key)
{
    $this->open();
    if (isset($_SESSION[$key])) {
        $value = $_SESSION[$key];
        unset($_SESSION[$key]);
        return $value;
    }
    return null;
}

            

Removes all session variables.

Source code

                public function removeAll()
{
    $this->open();
    foreach (array_keys($_SESSION) as $key) {
        unset($_SESSION[$key]);
    }
}

            

Removes all flash messages.

Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, it will be removed by this method.

See also:

Source code

                public function removeAllFlashes()
{
    $counters = $this->get($this->flashParam, []);
    foreach (array_keys($counters) as $key) {
        unset($_SESSION[$key]);
    }
    unset($_SESSION[$this->flashParam]);
}

            
public mixed removeFlash ( $key ) $key string

The key identifying the flash message. Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, it will be removed by this method.

return mixed

The removed flash message. Null if the flash message does not exist.

Source code

                public function removeFlash($key)
{
    $counters = $this->get($this->flashParam, []);
    $value = isset($_SESSION[$key], $counters[$key]) ? $_SESSION[$key] : null;
    unset($counters[$key], $_SESSION[$key]);
    $_SESSION[$this->flashParam] = $counters;
    return $value;
}

            

Adds a session variable.

If the specified name already exists, the old value will be overwritten.

public void set ( $key, $value ) $key string

Session variable name

$value mixed

Session variable value

Source code

                public function set($key, $value)
{
    $this->open();
    $_SESSION[$key] = $value;
}

            

Set cache limiter

Source code

                public function setCacheLimiter($cacheLimiter)
{
    $this->freeze();
    session_cache_limiter($cacheLimiter);
    $this->unfreeze();
}

            
public void setCookieParams ( array $value ) $value array

Cookie parameters, valid keys include: lifetime, path, domain, secure and httponly. Starting with Yii 2.0.21 sameSite is also supported. It requires PHP version 7.3.0 or higher. For security, an exception will be thrown if sameSite is set while using an unsupported version of PHP. To use this feature across different PHP versions check the version first. E.g. `php [

'sameSite' => PHP_VERSION_ID >= 70300 ? yii\web\Cookie::SAME_SITE_LAX : null,

] ` See https://owasp.org/www-community/SameSite for more information about sameSite.

throws yii\base\InvalidArgumentException

if the parameters are incomplete.

Source code

                public function setCookieParams(array $value)
{
    $this->_cookieParams = $value;
}

            

Sets a flash message.

A flash message will be automatically deleted after it is accessed in a request and the deletion will happen in the next request. If there is already an existing flash message with the same key, it will be overwritten by the new one.

See also:

public void setFlash ( $key, $value true, $removeAfterAccess true ) $key string

The key identifying the flash message. Note that flash messages and normal session variables share the same name space. If you have a normal session variable using the same name, its value will be overwritten by this method.

$value mixed

Flash message

$removeAfterAccess boolean

Whether the flash message should be automatically removed only if it is accessed. If false, the flash message will be automatically removed after the next request, regardless if it is accessed or not. If true (default value), the flash message will remain until after it is accessed.

Source code

                public function setFlash($key, $value = true, $removeAfterAccess = true)
{
    $counters = $this->get($this->flashParam, []);
    $counters[$key] = $removeAfterAccess ? -1 : 0;
    $_SESSION[$key] = $value;
    $_SESSION[$this->flashParam] = $counters;
}

            

Source code

                public function setGCProbability($value)
{
    $this->freeze();
    if ($value >= 0 && $value <= 100) {
        
        ini_set('session.gc_probability', floor($value * 21474836.47));
        ini_set('session.gc_divisor', 2147483647);
    } else {
        throw new InvalidArgumentException('GCProbability must be a value between 0 and 100.');
    }
    $this->unfreeze();
}

            

Sets the value indicating whether the current request has sent the session ID.

This method is provided so that you can override the default way of determining whether the session ID is sent.

Source code

                public function setHasSessionId($value)
{
    $this->_hasSessionId = $value;
}

            
public void setId ( $value ) $value string

The session ID for the current session

Source code

                public function setId($value)
{
    session_id($value);
}

            
public void setName ( $value ) $value string

The session name for the current session, must be an alphanumeric string. It defaults to "PHPSESSID".

Source code

                public function setName($value)
{
    $this->freeze();
    session_name($value);
    $this->unfreeze();
}

            

Source code

                public function setSavePath($value)
{
    $path = Yii::getAlias($value);
    if (is_dir($path)) {
        session_save_path($path);
    } else {
        throw new InvalidArgumentException("Session save path is not a valid directory: $value");
    }
}

            
public void setTimeout ( $value ) $value integer

The number of seconds after which data will be seen as 'garbage' and cleaned up

Source code

                public function setTimeout($value)
{
    $this->freeze();
    ini_set('session.gc_maxlifetime', $value);
    $this->unfreeze();
}

            

Sets the value indicating whether cookies should be used to store session IDs.

Three states are possible:

public void setUseCookies ( $value ) $value boolean|null

The value indicating whether cookies should be used to store session IDs.

Source code

                public function setUseCookies($value)
{
    $this->freeze();
    if ($value === false) {
        ini_set('session.use_cookies', '0');
        ini_set('session.use_only_cookies', '0');
    } elseif ($value === true) {
        ini_set('session.use_cookies', '1');
        ini_set('session.use_only_cookies', '1');
    } else {
        ini_set('session.use_cookies', '1');
        ini_set('session.use_only_cookies', '0');
    }
    $this->unfreeze();
}

            
public void setUseStrictMode ( $value ) $value boolean

Whether strict mode is enabled or not. When true this setting prevents the session component to use an uninitialized session ID. Note: Enabling useStrictMode on PHP < 5.5.2 is only supported with custom storage classes. Warning! Although enabling strict mode is mandatory for secure sessions, the default value of 'session.use-strict-mode' is 0.

Source code

                public function setUseStrictMode($value)
{
    if (PHP_VERSION_ID < 50502) {
        if ($this->getUseCustomStorage() || !$value) {
            self::$_useStrictModePolyfill = $value;
        } else {
            throw new InvalidConfigException('Enabling `useStrictMode` on PHP < 5.5.2 is only supported with custom storage classes.');
        }
    } else {
        $this->freeze();
        ini_set('session.use_strict_mode', $value ? '1' : '0');
        $this->unfreeze();
    }
}

            

Source code

                public function setUseTransparentSessionID($value)
{
    $this->freeze();
    ini_set('session.use_trans_sid', $value ? '1' : '0');
    $this->unfreeze();
}

            

Defined in: yii\base\Component::trigger()

Triggers an event.

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

Source code

                public function trigger($name, ?Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            
            if ($event->handled) {
                return;
            }
        }
    }
    
    Event::trigger($this, $name, $event);
}

            

Starts session and restores data from temporary variable

Source code

                protected function unfreeze()
{
    if (null !== $this->_frozenSessionData) {
        YII_DEBUG ? session_start() : @session_start();
        if ($this->getIsActive()) {
            Yii::info('Session unfrozen', __METHOD__);
        } else {
            $error = error_get_last();
            $message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
            Yii::error($message, __METHOD__);
        }
        $_SESSION = $this->_frozenSessionData;
        $this->_frozenSessionData = null;
    }
}

            

Updates the counters for flash messages and removes outdated flash messages.

This method should only be called once in init().

Source code

                protected function updateFlashCounters()
{
    $counters = $this->get($this->flashParam, []);
    if (is_array($counters)) {
        foreach ($counters as $key => $count) {
            if ($count > 0) {
                unset($counters[$key], $_SESSION[$key]);
            } elseif ($count == 0) {
                $counters[$key]++;
            }
        }
        $_SESSION[$this->flashParam] = $counters;
    } else {
        
        unset($_SESSION[$this->flashParam]);
    }
}

            

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4