diff --git a/.gitignore b/.gitignore index a7fc91d6..d41a109a 100644 --- a/.gitignore +++ b/.gitignore @@ -6,10 +6,12 @@ .*.sw* .*.un~ nbproject +doc/html/ tmp/ +vendor/ +zf-mkdoc-theme/ clover.xml composer.lock coveralls-upload.json phpunit.xml -vendor diff --git a/.travis.yml b/.travis.yml index 119c655a..90a549d7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,17 @@ branches: cache: directories: - - $HOME/.composer/cache + - $HOME/.composer/ + - $HOME/.local + - zf-mkdoc-theme + +env: + global: + - SITE_URL: https://zendframework.github.io/zend-session + - GH_USER_NAME: "Matthew Weier O'Phinney" + - GH_USER_EMAIL: matthew@weierophinney.net + - GH_REF: github.com/zendframework/zend-session.git + - secure: "ig2TftPXHnxHzO9ho44sj5PnWfoKlHt6el7jzU80udzFIyhFBhgTGVC1I2kNLDJ8gvZitfuogxR/XYRMSTl2Pe/Te8hbza+PShlrqSG9C3PwApUof2BiuTNcIYjAp+RxQhjluKl/SmloUQhS8C1eb0WSnVfCjTQjlf+CIaJ+m1YaSVIkFjh3IyJgAglPdSB8Avst7xpYZF0cK723ZtyApUsuWoSHQjof54ziN+YDqWBfNovR1rWTmTNCfsBOHIhKTFhV0duXE+3MCnSTb3HogNtBuVKB842SU+8lnU1xaV7Ty3fE9nIB/j/mLC+MAGoZJshAv/o6ui3Y/41+oATllLgFnsy6+KvN6NiH449h2zMMy6cF3FILrYGpLpBafP3Yjxssdz9UaQtuNFRflGNpcoDAkw0x7+w5vX+yH7qibW4HQqyZLxeefZ22+F6NRPmsanJdPtZ7LKHMani3lNq9zWetNL8XaREwclSDK50HHhIygMAejr0OU5fVHmk30yZqGdiEcAoiabwgENt7ndeQPW6u3OOfzteo7dDZwWdZLbB1JWFmYbwQH4ek7KTIpQ8utH53qwg2PeLYg0W0y4g9Y46gGzaBIlsEE6RAIE8b8O3f6dPzRtTuHTJCS+AGQX61bqQUsph9jEIBsmVTVUHXNmLmOZnthPbzpPfza8v3EQM=" services: - mongodb @@ -27,6 +37,13 @@ matrix: - php: 5.6 env: - EXECUTE_TEST_COVERALLS=true + - DEPLOY_DOCS="$(if [[ $TRAVIS_BRANCH == 'master' && $TRAVIS_PULL_REQUEST == 'false' ]]; then echo -n 'true' ; else echo -n 'false' ; fi)" + - PATH="$HOME/.local/bin:$PATH" + - php: 5.6 + env: + - EXECUTE_TEST_COVERALLS=true + - DEPLOY_DOCS="$(if [[ $TRAVIS_BRANCH == 'master' && $TRAVIS_PULL_REQUEST == 'false' ]]; then echo -n 'true' ; else echo -n 'false' ; fi)" + - PATH="$HOME/.local/bin:$PATH" - php: 5.6 env: - EVENT_MANAGER_VERSION="^2.6.2" @@ -65,6 +82,10 @@ script: - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/phpunit --coverage-clover clover.xml ; fi - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then ./vendor/bin/phpunit ; fi - if [[ $EXECUTE_CS_CHECK == 'true' ]]; then ./vendor/bin/php-cs-fixer fix -v --diff --dry-run ; fi + - if [[ $DEPLOY_DOCS == "true" && "$TRAVIS_TEST_RESULT" == "0" ]]; then wget -O theme-installer.sh "https://raw.githubusercontent.com/zendframework/zf-mkdoc-theme/master/theme-installer.sh" ; chmod 755 theme-installer.sh ; ./theme-installer.sh ; fi + +after_success: + - if [[ $DEPLOY_DOCS == "true" ]]; then echo "Preparing to build and deploy documentation" ; ./zf-mkdoc-theme/deploy.sh ; echo "Completed deploying documentation" ; fi after_script: - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/coveralls ; fi diff --git a/CHANGELOG.md b/CHANGELOG.md index 0eb15059..a79381e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,12 @@ All notable changes to this project will be documented in this file, in reverse chronological order by release. -## 2.7.1 - TBD +## 2.7.1 - 2016-05-11 ### Added -- Nothing. +- [#40](https://github.com/zendframework/zend-session/pull/40) adds and + publishes the documentation to https://zendframework.github.io/zend-session/ ### Deprecated diff --git a/README.md b/README.md index 74a16b7c..128172ac 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,7 @@ [![Build Status](https://secure.travis-ci.org/zendframework/zend-session.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-session) [![Coverage Status](https://coveralls.io/repos/zendframework/zend-session/badge.svg?branch=master)](https://coveralls.io/r/zendframework/zend-session?branch=master) -`Zend\Session` is a component to manage PHP session using an object oriented -interface. - +zend-session manages PHP sessions using an object oriented interface. - File issues at https://github.com/zendframework/zend-session/issues -- Documentation is at http://framework.zend.com/manual/current/en/index.html#zend-session +- Documentation is at https://zendframework.github.io/zend-session/ diff --git a/doc/book/zend.session.config.md b/doc/book/config.md similarity index 71% rename from doc/book/zend.session.config.md rename to doc/book/config.md index a2f6ee0a..3725551f 100644 --- a/doc/book/zend.session.config.md +++ b/doc/book/config.md @@ -1,14 +1,15 @@ # Session Config -Zend Framework comes with a standard set of config classes which are ready for you to use. Config -handles setting various configuration such as where a cookie lives, lifetime, including several bits -to configure ext/session when using `Zend\Session\Config\SessionConfig`. +zend-session comes with a standard set of config classes, allowing setting where +a cookie lives, session lifetime, and even configuration of ext/session when +using `Zend\Session\Config\SessionConfig`. ## Standard Config -`Zend\Session\Config\StandardConfig` provides you a basic interface for implementing sessions when -*not* leveraging ext/session. This is utilized more for specialized cases such as when you might -have session management done by another system. +`Zend\Session\Config\StandardConfig` provides the base interface for +configuring sessions when *not* leveraging ext/session. This is utilized more +for specialized cases, such as when you might have session management done by +another system, or when testing. ### Basic Configuration Options @@ -35,8 +36,6 @@ Option | Data Type | Description ### Basic Usage -A basic example is one like the following: - ```php use Zend\Session\Config\StandardConfig; use Zend\Session\SessionManager; @@ -51,14 +50,15 @@ $manager = new SessionManager($config); ## Session Config -`Zend\Session\Config\SessionConfig` provides you a basic interface for implementing sessions when -that leverage PHP's ext/session. Most configuration options configure either the -`Zend\Session\Storage` OR configure ext/session directly. +`Zend\Session\Config\SessionConfig` provides an interface for configuring +sessions that leverage PHP's ext/session. Most configuration options configure +either the `Zend\Session\Storage` OR configure ext/session directly. ### Basic Configuration Options -The following configuration options are defined by `Zend\Session\Config\SessionConfig`, note that it -inherits all configuration from `Zend\Session\Config\StandardConfig`. +The following configuration options are defined by `Zend\Session\Config\SessionConfig`; +note that it inherits all configuration from +`Zend\Session\Config\StandardConfig`. Option | Data Type | Description ------------------- | --------- | ----------- @@ -71,8 +71,6 @@ Option | Data Type | Description ### Basic Usage -A basic example is one like the following: - ```php use Zend\Session\Config\SessionConfig; use Zend\Session\SessionManager; @@ -87,11 +85,12 @@ $manager = new SessionManager($config); ### Service Manager Factory -`Zend\Session` ships with a Service Manager <zend.service-manager.intro> factory which reads -configuration data from the application configuration and injects a corresponding instance of -`Zend\Session\Config\SessionConfig` into the session manager automatically. +zend-session ships with a [zend-servicemanager](https://zendframework.github.io/zend-servicemanager/) +factory which reads configuration data from the application configuration and +injects a corresponding instance of `Zend\Session\Config\SessionConfig` into the +session manager automatically. -To use this factory, you first need to register it with the Service Manager by adding the +To use this factory, you first need to register it with the service manager by adding the appropriate factory definition: ```php @@ -102,8 +101,14 @@ appropriate factory definition: ], ``` -Then place your application's session configuration in the root-level configuration key -`session_config`: +> #### Automated factory registration +> +> Starting with zend-mvc v3, if you are using the [component installer](https://zendframework.github.io/zend-component-installer) +> in your application, the above registration will be made automatically for +> you when you install zend-session. + +Then place your application's session configuration in the root-level +configuration key `session_config`: ```php 'session_config' => [ @@ -121,7 +126,8 @@ Option | Data Type | Description ## Custom Configuration -In the event that you prefer to create your own session configuration; you *must* implement -`Zend\Session\Config\ConfigInterface` which contains the basic interface for items needed when -implementing a session. This includes cookie configuration, lifetime, session name, save path and an -interface for getting and setting options. +In the event that you prefer to create your own session configuration; you +*must* implement `Zend\Session\Config\ConfigInterface` which contains the basic +interface for items needed when implementing a session. This includes cookie +configuration, lifetime, session name, save path, and an interface for getting +and setting options. diff --git a/doc/book/zend.session.container.md b/doc/book/container.md similarity index 55% rename from doc/book/zend.session.container.md rename to doc/book/container.md index 82e6faee..856fbd33 100644 --- a/doc/book/zend.session.container.md +++ b/doc/book/container.md @@ -1,12 +1,13 @@ # Session Container -`Zend\Session\Container` instances provide the primary API for manipulating session data in the Zend -Framework. Containers are used to segregate all session data, although a default namespace exists -for those who only want one namespace for all their session data. +`Zend\Session\Container` instances provide the primary API for manipulating +session data in zend-session. Containers are used to segregate all session +data, although a default namespace exists for those who only want one namespace +for all their session data. -Each instance of `Zend\Session\Container` corresponds to an entry of the `Zend\Session\Storage`, -where the namespace is used as the key. `Zend\Session\Container` itself is an instance of an -ArrayObject. +Each instance of `Zend\Session\Container` corresponds to an entry of the +`Zend\Session\Storage`, where the namespace is used as the key. +`Zend\Session\Container` itself is an instance of an `ArrayObject`. ## Basic Usage @@ -19,8 +20,8 @@ $container->item = 'foo'; ## Setting the Default Session Manager -In the event you are using multiple session managers or prefer to be explicit, the default session -manager that is utilized can be explicitly set. +In the event you are using multiple session managers or prefer to be explicit, +the default session manager that is utilized can be explicitly set. ```php use Zend\Session\Container; diff --git a/doc/book/index.html b/doc/book/index.html new file mode 100644 index 00000000..9b100efc --- /dev/null +++ b/doc/book/index.html @@ -0,0 +1,10 @@ +
+
+

zend-session

+ +

Object-oriented interface to PHP sessions and storage.

+ +
$ composer require zendframework/zend-session
+
+
+ diff --git a/doc/book/index.md b/doc/book/index.md new file mode 100644 index 00000000..fe840054 --- /dev/null +++ b/doc/book/index.md @@ -0,0 +1 @@ +../../README.md \ No newline at end of file diff --git a/doc/book/manager.md b/doc/book/manager.md new file mode 100644 index 00000000..0dc2e92e --- /dev/null +++ b/doc/book/manager.md @@ -0,0 +1,176 @@ +# Session Manager + +The session manager, `Zend\Session\SessionManager`, is the class responsible for +all aspects of session management. It initializes configuration, storage, and +save handlers. Additionally the session manager can be injected into the +session container to provide a wrapper or namespace around your session data. + +The session manager is responsible for starting a session, testing if a session +exists, writing to the session, regenerating the session identifier, setting the +session time-to-live, and destroying the session. The session manager can +validate sessions from a validator chain to ensure that the session data is +correct. + +## Initializing the Session Manager + +Generally speaking, you will always want to initialize the session manager and +ensure that your application was responsible for its initialization; this puts +in place a simple solution to prevent against session fixation. Generally you +will setup configuration and then inside of an application module bootstrap the +session manager. + +Additionally you will likely want to supply validators to prevent against +session hijacking. + +The following illustrates how you may configure the session manager by setting +options in your local or global config: + +```php +use Zend\Session; + +return [ + 'session' => [ + 'config' => [ + 'class' => Session\Config\SessionConfig::class, + 'options' => [ + 'name' => 'myapp', + ], + ], + 'storage' => Session\Storage\SessionArrayStorage::class, + 'validators' => [ + Session\Validator\RemoteAddr::class, + Session\Validator\HttpUserAgent::class, + ], + ], +]; +``` + +The following illustrates how you might utilize the above configuration to +create the session manager: + +```php +use Zend\Session\SessionManager; +use Zend\Session\Config\SessionConfig; +use Zend\Session\Container; +use Zend\Session\SessionManager; +use Zend\Session\Validator; + +class Module +{ + public function onBootstrap($e) + { + $eventManager = $e->getApplication()->getEventManager(); + $moduleRouteListener = new ModuleRouteListener(); + $moduleRouteListener->attach($eventManager); + $this->bootstrapSession($e); + } + + public function bootstrapSession($e) + { + $session = $e->getApplication() + ->getServiceManager() + ->get(SessionManager::class); + $session->start(); + + $container = new Container('initialized'); + + if (isset($container->init)) { + return; + } + + $serviceManager = $e->getApplication()->getServiceManager(); + $request = $serviceManager->get('Request'); + + $session->regenerateId(true); + $container->init = 1; + $container->remoteAddr = $request->getServer()->get('REMOTE_ADDR'); + $container->httpUserAgent = $request->getServer()->get('HTTP_USER_AGENT'); + + $config = $serviceManager->get('Config'); + if (! isset($config['session'])) { + return; + } + + $sessionConfig = $config['session']; + + if (! isset($sessionConfig['validators'])) { + return; + } + + $chain = $session->getValidatorChain(); + + foreach ($sessionConfig['validators'] as $validator) { + switch ($validator) { + case Validator\HttpUserAgent::class: + $validator = new $validator($container->httpUserAgent); + break; + case Validator\RemoteAddr::class: + $validator = new $validator($container->remoteAddr); + break; + default: + $validator = new $validator(); + } + + $chain->attach('session.validate', array($validator, 'isValid')); + } + } + + public function getServiceConfig() + { + return [ + 'factories' => [ + SessionManager::class => function ($container) { + $config = $container->get('config'); + if (! isset($config['session'])) { + $sessionManager = new SessionManager(); + Container::setDefaultManager($sessionManager); + return $sessionManager; + } + + $session = $config['session']; + + $sessionConfig = null; + if (isset($session['config'])) { + $class = isset($session['config']['class']) + ? $session['config']['class'] + : SessionConfig::class; + + $options = isset($session['config']['options']) + ? $session['config']['options'] + : []; + + $sessionConfig = new $class(); + $sessionConfig->setOptions($options); + } + + $sessionStorage = null; + if (isset($session['storage'])) { + $class = $session['storage']; + $sessionStorage = new $class(); + } + + $sessionSaveHandler = null; + if (isset($session['save_handler'])) { + // class should be fetched from service manager + // since it will require constructor arguments + $sessionSaveHandler = $container->get($session['save_handler']); + } + + $sessionManager = new SessionManager( + $sessionConfig, + $sessionStorage, + $sessionSaveHandler + ); + + Container::setDefaultManager($sessionManager); + return $sessionManager; + }, + ], + ]; + } +} +``` + +When you create a new `Zend\Session\Container` (see +[Session Container](container.md) page) in a controller, for example, it will +use the session configured above. diff --git a/doc/book/save-handler.md b/doc/book/save-handler.md new file mode 100644 index 00000000..6741d9c5 --- /dev/null +++ b/doc/book/save-handler.md @@ -0,0 +1,108 @@ +# Session Save Handlers + +zend-session comes with a set of save handler classes. Save handlers themselves +are decoupled from PHP's save handler functions and are only implemented as a +PHP save handler when utilized in conjunction with +`Zend\Session\SessionManager`. + +## Cache + +`Zend\Session\SaveHandler\Cache` allows you to provide an instance of +`Zend\Cache\Storage\Adapter\AdapterInterface` to be utilized as a session save +handler. Generally if you are utilizing the `Cache` save handler; you are likely +using products such as memcached. + +### Basic usage + +A basic example is one like the following: + +```php +use Zend\Cache\StorageFactory; +use Zend\Session\SaveHandler\Cache; +use Zend\Session\SessionManager; + +$cache = StorageFactory::factory([ + 'adapter' => [ + 'name' => 'memcached', + 'options' => [ + 'server' => '127.0.0.1', + ], + ], +]); + +$saveHandler = new Cache($cache); +$manager = new SessionManager(); +$manager->setSaveHandler($saveHandler); +``` + +## DbTableGateway + +`Zend\Session\SaveHandler\DbTableGateway` allows you to utilize +`Zend\Db\TableGateway\TableGatewayInterface` implementations as a session save +handler. Setup of a `DbTableGateway` save handler requires an instance of +`Zend\Db\TableGateway\TableGatewayInterface` and an instance of +`Zend\Session\SaveHandler\DbTableGatewayOptions`. In the most basic setup, a +`TableGateway` object and using the defaults of the `DbTableGatewayOptions` will +provide you with what you need. + +### Creating the database table + +```sql +CREATE TABLE `session` ( + `id` char(32), + `name` char(32), + `modified` int, + `lifetime` int, + `data` text, + PRIMARY KEY (`id`, `name`) +); +``` + +### Basic usage + +```php +use Zend\Db\TableGateway\TableGateway; +use Zend\Session\SaveHandler\DbTableGateway; +use Zend\Session\SaveHandler\DbTableGatewayOptions; +use Zend\Session\SessionManager; + +$tableGateway = new TableGateway('session', $adapter); +$saveHandler = new DbTableGateway($tableGateway, new DbTableGatewayOptions()); +$manager = new SessionManager(); +$manager->setSaveHandler($saveHandler); +``` + +## MongoDB + +`Zend\Session\SaveHandler\MongoDB` allows you to provide a MongoDB collection to +be utilized as a session save handler. You provide the options in the +`Zend\Session\SaveHandler\MongoDBOptions` class. You must install the +[mongodb PHP extensions](http://php.net/mongodb) and the +[MongoDB PHP library](https://github.com/mongodb/mongo-php-library). + +### Basic Usage + +```php +use MongoDB\Client; +use Zend\Session\SaveHandler\MongoDB; +use Zend\Session\SaveHandler\MongoDBOptions; +use Zend\Session\SessionManager; + +$mongoClient = new Client(); +$options = new MongoDBOptions([ + 'database' => 'myapp', + 'collection' => 'sessions', +]); +$saveHandler = new MongoDB($mongoClient, $options); +$manager = new SessionManager(); +$manager->setSaveHandler($saveHandler); +``` + +## Custom Save Handlers + +There may be cases where you want to create a save handler. Creating a custom +save handler is much like creating a custom PHP save handler, with minor +differences. All zend-session-compatible save handlers *must* implement +`Zend\Session\SaveHandler\SaveHandlerInterface`. Additionally, if your save +handler has configurable functionality, you will also need to create an options +class. diff --git a/doc/book/storage.md b/doc/book/storage.md new file mode 100644 index 00000000..021f79f1 --- /dev/null +++ b/doc/book/storage.md @@ -0,0 +1,88 @@ +# Session Storage + +zend-session comes with a standard set of storage handlers. Storage handlers are +the intermediary between when the session starts and when the session writes and +closes. The default session storage is +`Zend\Session\Storage\SessionArrayStorage`. + +## Array Storage + +`Zend\Session\Storage\ArrayStorage` provides a facility to store all information +in an `ArrayObject`. This storage method is likely incompatible with 3rd party +libraries and all properties will be inaccessible through the `$_SESSION` +superglobal. Additionally `ArrayStorage` will not automatically repopulate the +storage container in the case of each new request and would have to manually be +re-populated. + +### Basic Usage + +```php +use Zend\Session\Storage\ArrayStorage; +use Zend\Session\SessionManager; + +$populateStorage = ['foo' => 'bar']; +$storage = new ArrayStorage($populateStorage); +$manager = new SessionManager(); +$manager->setStorage($storage); +``` + +## Session Storage + +`Zend\Session\Storage\SessionStorage` replaces `$_SESSION,` providing a facility +to store all information in an `ArrayObject`. This means that it may not be +compatible with 3rd party libraries, although information stored in the +`$_SESSION` superglobal should be available in other scopes. + +### Basic Usage + +```php +use Zend\Session\Storage\SessionStorage; +use Zend\Session\SessionManager; + +$manager = new SessionManager(); +$manager->setStorage(new SessionStorage()); +``` + +## Session Array Storage + +`Zend\Session\Storage\SessionArrayStorage` provides a facility to store all +information directly in the `$_SESSION` superglobal. This storage class provides +the most compatibility with 3rd party libraries and allows for directly storing +information into `$_SESSION`. + +### Basic Usage + +```php +use Zend\Session\Storage\SessionArrayStorage; +use Zend\Session\SessionManager; + +$manager = new SessionManager(); +$manager->setStorage(new SessionArrayStorage()); +``` + +## Custom Storage + +To create a custom storage container, you *must* implement +`Zend\Session\Storage\StorageInterface`. This interface extends each of +`ArrayAccess`, `Traversable`, `Serializable`, and `Countable`, and it is in the +methods those define that the majority of implementation occurs. The following +methods must also be implemented: + +```php +public function getRequestAccessTime() : int; + +public function lock(int|string $key = null) : void; +public function isLocked(int|string $key = null) : bool; +public function unlock(int|string $key = null) : void; + +public function markImmutable() : void; +public function isImmutable() : bool; + +public function setMetadata(string $key, mixed $value, bool $overwriteArray = false) : void; +public function getMetadata(string $key = null) : mixed; + +public function clear(inst|string $key = null) : void; + +public function fromArray(array $array) : void; +public function toArray(bool $metaData = false) : array; +``` diff --git a/doc/book/validator.md b/doc/book/validator.md new file mode 100644 index 00000000..cd8e32f7 --- /dev/null +++ b/doc/book/validator.md @@ -0,0 +1,46 @@ +# Session Validators + +Session validators provide protections against session hijacking. + +## Http User Agent + +`Zend\Session\Validator\HttpUserAgent` provides a validator to check the session +against the originally stored `$_SERVER['HTTP_USER_AGENT']` variable. Validation +will fail in the event that this does not match and throws an exception in +`Zend\Session\SessionManager` after `session_start()` has been called. + +### Basic Usage + +```php +use Zend\Session\Validator\HttpUserAgent; +use Zend\Session\SessionManager; + +$manager = new SessionManager(); +$manager->getValidatorChain() + ->attach('session.validate', [new HttpUserAgent(), 'isValid']); +``` + +## Remote Addr + +`Zend\Session\Validator\RemoteAddr` provides a validator to check the session +against the originally stored `$_SERVER['REMOTE_ADDR']` variable. Validation +will fail in the event that this does not match and throws an exception in +`Zend\Session\SessionManager` after `session_start()` has been called. + +### Basic Usage + +```php +use Zend\Session\Validator\RemoteAddr; +use Zend\Session\SessionManager; + +$manager = new SessionManager(); +$manager->getValidatorChain() + ->attach('session.validate', [new RemoteAddr(), 'isValid']); +``` + +## Custom Validators + +You may want to provide your own custom validators to validate against other +items from storing a token and validating a token to other various techniques. +To create a custom validator you *must* implement the validation interface +`Zend\Session\Validator\ValidatorInterface`. diff --git a/doc/book/zend.session.manager.md b/doc/book/zend.session.manager.md deleted file mode 100644 index c565d41b..00000000 --- a/doc/book/zend.session.manager.md +++ /dev/null @@ -1,168 +0,0 @@ -# Session Manager - -The session manager, `Zend\Session\SessionManager`, is a class that is responsible for all aspects -of session management. It initializes and configures configuration, storage and save handling. -Additionally the session manager can be injected into the session container to provide a wrapper or -namespace around your session data. - -The session manager is responsible for session start, session exists, session write, regenerate id, -time to live and session destroy. The session manager can validate sessions from a validator chain -to ensure that the session data is indeed correct. - -## Initializing the Session Manager - -Generally speaking you will always want to initialize the session manager and ensure that you had -initialized it on your end; this puts in place a simple solution to prevent against session -fixation. Generally you will setup configuration and then inside of your Application module -bootstrap the session manager. - -Additionally you will likely want to supply validators to prevent against session hijacking. - -The following illustrates how you may configure session manager by setting options in your local or -global config: - -```php -return array( - 'session' => array( - 'config' => array( - 'class' => 'Zend\Session\Config\SessionConfig', - 'options' => array( - 'name' => 'myapp', - ), - ), - 'storage' => 'Zend\Session\Storage\SessionArrayStorage', - 'validators' => array( - 'Zend\Session\Validator\RemoteAddr', - 'Zend\Session\Validator\HttpUserAgent', - ), - ), -); -``` - -The following illustrates how you might utilize the above configuration to create the session -manager: - -```php -use Zend\Session\SessionManager; -use Zend\Session\Container; - -class Module -{ - public function onBootstrap($e) - { - $eventManager = $e->getApplication()->getEventManager(); - $moduleRouteListener = new ModuleRouteListener(); - $moduleRouteListener->attach($eventManager); - $this->bootstrapSession($e); - } - - public function bootstrapSession($e) - { - $session = $e->getApplication() - ->getServiceManager() - ->get('Zend\Session\SessionManager'); - $session->start(); - - $container = new Container('initialized'); - if (!isset($container->init)) { - $serviceManager = $e->getApplication()->getServiceManager(); - $request = $serviceManager->get('Request'); - - $session->regenerateId(true); - $container->init = 1; - $container->remoteAddr = $request->getServer()->get('REMOTE_ADDR'); - $container->httpUserAgent = $request->getServer()->get('HTTP_USER_AGENT'); - - $config = $serviceManager->get('Config'); - if (!isset($config['session'])) { - return; - } - - $sessionConfig = $config['session']; - if (isset($sessionConfig['validators'])) { - $chain = $session->getValidatorChain(); - - foreach ($sessionConfig['validators'] as $validator) { - switch ($validator) { - case 'Zend\Session\Validator\HttpUserAgent': - $validator = new $validator($container->httpUserAgent); - break; - case 'Zend\Session\Validator\RemoteAddr': - $validator = new $validator($container->remoteAddr); - break; - default: - $validator = new $validator(); - } - - $chain->attach('session.validate', array($validator, 'isValid')); - } - } - } - } - - public function getServiceConfig() - { - return array( - 'factories' => array( - 'Zend\Session\SessionManager' => function ($sm) { - $config = $sm->get('config'); - if (isset($config['session'])) { - $session = $config['session']; - - $sessionConfig = null; - if (isset($session['config'])) { - $class = isset($session['config']['class']) ? -$session['config']['class'] : 'Zend\Session\Config\SessionConfig'; - $options = isset($session['config']['options']) ? -$session['config']['options'] : array(); - $sessionConfig = new $class(); - $sessionConfig->setOptions($options); - } - - $sessionStorage = null; - if (isset($session['storage'])) { - $class = $session['storage']; - $sessionStorage = new $class(); - } - - $sessionSaveHandler = null; - if (isset($session['save_handler'])) { - // class should be fetched from service manager since it will require -constructor arguments - $sessionSaveHandler = $sm->get($session['save_handler']); - } - - $sessionManager = new SessionManager($sessionConfig, $sessionStorage, -$sessionSaveHandler); - } else { - $sessionManager = new SessionManager(); - } - Container::setDefaultManager($sessionManager); - return $sessionManager; - }, - ), - ); - } -} -``` - -When you create a new `Zend\Session\Container` (see Session Container page) in a controller for -example, it will use the session configured above. - -## Session Compatibility - -In order to work with other 3rd party libraries and share sessions across software that may not be -ZF2 related; you will need to ensure that you still provide access to the ZF2 autoloader as well as -module autoloading. - -In the shared software make certain before the session starts that you bootstrap the ZF2 autoloader -and initialize the ZF2 Application. - -```php -$cwd = getcwd(); -chdir('/path/to/zf2-application'); -require 'init_autoloader.php'; -Zend\Mvc\Application::init(require 'config/application.config.php'); -chdir($cwd); -session_start(); -``` diff --git a/doc/book/zend.session.save-handler.md b/doc/book/zend.session.save-handler.md deleted file mode 100644 index 0b2cb11b..00000000 --- a/doc/book/zend.session.save-handler.md +++ /dev/null @@ -1,104 +0,0 @@ -# Session Save Handlers - -Zend Framework comes with a standard set of save handler classes which are ready for you to use. -Save Handlers themselves are decoupled from PHP's save handler functions and are *only* implemented -as a PHP save handler when utilized in conjunction with `Zend\Session\SessionManager`. - -## Cache - -`Zend\Session\SaveHandler\Cache` allows you to provide an instance of `Zend\Cache` to be utilized as -a session save handler. Generally if you are utilizing the Cache save handler; you are likely using -products such as memcached. - -### Basic usage - -A basic example is one like the following: - -```php -use Zend\Cache\StorageFactory; -use Zend\Session\SaveHandler\Cache; -use Zend\Session\SessionManager; - -$cache = StorageFactory::factory(array( - 'adapter' => array( - 'name' => 'memcached', - 'options' => array( - 'server' => '127.0.0.1', - ), - ) -)); -$saveHandler = new Cache($cache); -$manager = new SessionManager(); -$manager->setSaveHandler($saveHandler); -``` - -## DbTableGateway - -`Zend\Session\SaveHandler\DbTableGateway` allows you to utilize `Zend\Db` as a session save handler. -Setup of the DbTableGateway requires an instance of `Zend\Db\TableGateway\TableGateway` and an -instance of `Zend\Session\SaveHandler\DbTableGatewayOptions`. In the most basic setup, a -TableGateway object and using the defaults of the DbTableGatewayOptions will provide you with what -you need. - -### Creating the database table - -```sql -CREATE TABLE `session` ( - `id` char(32), - `name` char(32), - `modified` int, - `lifetime` int, - `data` text, - PRIMARY KEY (`id`, `name`) -); -``` - -### Basic usage - -A basic example is one like the following: - -```php -use Zend\Db\TableGateway\TableGateway; -use Zend\Session\SaveHandler\DbTableGateway; -use Zend\Session\SaveHandler\DbTableGatewayOptions; -use Zend\Session\SessionManager; - -$tableGateway = new TableGateway('session', $adapter); -$saveHandler = new DbTableGateway($tableGateway, new DbTableGatewayOptions()); -$manager = new SessionManager(); -$manager->setSaveHandler($saveHandler); -``` - -## MongoDB - -`Zend\Session\SaveHandler\MongoDB` allows you to provide a MongoDB instance to be utilized as a -session save handler. You provide the options in the `Zend\Session\SaveHandler\MongoDBOptions` -class. You must install the [mongodb PHP extensions](http://php.net/manual/en/set.mongodb.php) and the -[MongoDB PHP library](https://github.com/mongodb/mongo-php-library). - -### Basic Usage - -A basic example is one like the following: - -```php -use MongoDB\Client; -use Zend\Session\SaveHandler\MongoDB; -use Zend\Session\SaveHandler\MongoDBOptions; -use Zend\Session\SessionManager; - -$mongoClient = new Client(); -$options = new MongoDBOptions(array( - 'database' => 'myapp', - 'collection' => 'sessions', -)); -$saveHandler = new MongoDB($mongoClient, $options); -$manager = new SessionManager(); -$manager->setSaveHandler($saveHandler); -``` - -## Custom Save Handlers - -There may be cases where you want to create a save handler where a save handler currently does not -exist. Creating a custom save handler is much like creating a custom PHP save handler. All save -handlers *must* implement `Zend\Session\SaveHandler\SaveHandlerInterface`. Generally if your save -handler has options you will create another options class for configuration of the save handler. diff --git a/doc/book/zend.session.storage.md b/doc/book/zend.session.storage.md deleted file mode 100644 index fa72acf9..00000000 --- a/doc/book/zend.session.storage.md +++ /dev/null @@ -1,70 +0,0 @@ -# Session Storage - -Zend Framework comes with a standard set of storage classes which are ready for you to use. Storage -handlers is the intermediary between when the session starts and when the session writes and closes. -The default session storage is `Zend\Session\Storage\SessionArrayStorage`. - -## Array Storage - -`Zend\Session\Storage\ArrayStorage` provides a facility to store all information in an ArrayObject. -This storage method is likely incompatible with 3rd party libraries and all properties will be -inaccessible through the `$_SESSION` property. Additionally ArrayStorage will not automatically -repopulate the storage container in the case of each new request and would have to manually be -re-populated. - -### Basic Usage - -A basic example is one like the following: - -```php -use Zend\Session\Storage\ArrayStorage; -use Zend\Session\SessionManager; - -$populateStorage = array('foo' => 'bar'); -$storage = new ArrayStorage($populateStorage); -$manager = new SessionManager(); -$manager->setStorage($storage); -``` - -## Session Storage - -`Zend\Session\Storage\SessionStorage` replaces `$_SESSION` providing a facility to store all -information in an ArrayObject. This means that it may not be compatible with 3rd party libraries. -Although information stored in the `$_SESSION` superglobal should be available in other scopes. - -### Basic Usage - -A basic example is one like the following: - -```php -use Zend\Session\Storage\SessionStorage; -use Zend\Session\SessionManager; - -$manager = new SessionManager(); -$manager->setStorage(new SessionStorage()); -``` - -## Session Array Storage - -`Zend\Session\Storage\SessionArrayStorage` provides a facility to store all information directly in -the `$_SESSION` superglobal. This storage class provides the most compatibility with 3rd party -libraries and allows for directly storing information into `$_SESSION`. - -### Basic Usage - -A basic example is one like the following: - -```php -use Zend\Session\Storage\SessionArrayStorage; -use Zend\Session\SessionManager; - -$manager = new SessionManager(); -$manager->setStorage(new SessionArrayStorage()); -``` - -## Custom Storage - -In the event that you prefer a different type of storage; to create a new custom storage container, -you *must* implement `Zend\Session\Storage\StorageInterface` which is mostly in implementing -ArrayAccess, Traversable, Serializable and Countable. StorageInterface defines some additional -functionality that must be implemented. diff --git a/doc/book/zend.session.validator.md b/doc/book/zend.session.validator.md deleted file mode 100644 index 2a52fa7c..00000000 --- a/doc/book/zend.session.validator.md +++ /dev/null @@ -1,50 +0,0 @@ -# Session Validators - -Session validators provide various protection against session hijacking. Session hijacking in -particular has various drawbacks when you are protecting against it. Such as an IP address may -change from the end user depending on their ISP; or a browsers user agent may change during the -request either by a web browser extension OR an upgrade that retains session cookies. - -## Http User Agent - -`Zend\Session\Validator\HttpUserAgent` provides a validator to check the session against the -originally stored `$_SERVER['HTTP_USER_AGENT']` variable. Validation will fail in the event that -this does not match and throws an exception in `Zend\Session\SessionManager` after `session_start()` -has been called. - -### Basic Usage - -A basic example is one like the following: - -```php -use Zend\Session\Validator\HttpUserAgent; -use Zend\Session\SessionManager; - -$manager = new SessionManager(); -$manager->getValidatorChain()->attach('session.validate', array(new HttpUserAgent(), 'isValid')); -``` - -## Remote Addr - -`Zend\Session\Validator\RemoteAddr` provides a validator to check the session against the originally -stored `$_SERVER['REMOTE_ADDR']` variable. Validation will fail in the event that this does not -match and throws an exception in `Zend\Session\SessionManager` after `session_start()` has been -called. - -### Basic Usage - -A basic example is one like the following: - -```php -use Zend\Session\Validator\RemoteAddr; -use Zend\Session\SessionManager; - -$manager = new SessionManager(); -$manager->getValidatorChain()->attach('session.validate', array(new RemoteAddr(), 'isValid')); -``` - -## Custom Validators - -You may want to provide your own custom validators to validate against other items from storing a -token and validating a token to other various techniques. To create a custom validator you *must* -implement the validation interface `Zend\Session\Validator\ValidatorInterface`. diff --git a/doc/bookdown.json b/doc/bookdown.json deleted file mode 100644 index 6766ffd6..00000000 --- a/doc/bookdown.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "title": "Zend\\Session", - "target": "html/", - "content": [ - "book/zend.session.config.md", - "book/zend.session.container.md", - "book/zend.session.manager.md", - "book/zend.session.save-handler.md", - "book/zend.session.storage.md", - "book/zend.session.validator.md" - ] -} \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml new file mode 100644 index 00000000..6de66bea --- /dev/null +++ b/mkdocs.yml @@ -0,0 +1,15 @@ +docs_dir: doc/book +site_dir: doc/html +pages: + - index.md + - Reference: + - "Session Config": config.md + - "Session Container": container.md + - "Session Manager": manager.md + - "Session Save Handlers": save-handler.md + - "Session Storage": storage.md + - "Session Validators": validator.md +site_name: zend-session +site_description: zend-session +repo_url: 'https://github.com/zendframework/zend-session' +copyright: 'Copyright (c) 2016 Zend Technologies USA Inc.'