воскресенье, 25 декабря 2011 г.

PHP sessions across sub domains

Params:
PHP-5.3, Apache-2.2

Problem:
I need a single session for mysite.com and admin.mysite.com domains. I would login on main domain mysite.com, and will be already authorized on sub domains like admin.mysite.com.


Solution:
In script before session start need too setup this session parameters:
session.cookie_path = "/"
session.cookie_domain = ".mysite.com" - dot at the beginning is important, it specify use same sessions on sub domains

Example:
Example for Zend Framework application.


Define site domain name value:
*** public/index.php ***
...
defined('SITE_DOMAIN_NAME')
|| define('SITE_DOMAIN_NAME', (getenv('SITE_DOMAIN_NAME') ? getenv('SITE_DOMAIN_NAME') : 'mysite.com'));
...
It seems, if server value SITE_DOMAIN_NAME is not defined, craete it. We will use it in config file.

You can define SITE_DOMAIN_NAME in .htaccess file, Anyway he need to be configured on every server separately.

*** public/.htaccess ***
...
SetEnv SITE_DOMAIN_NAME mysite.com
...

Further I set session values in config file
*** application/configs/application.ini ***
[production]
...
local.session.cookie_path = "/"
local.session.cookie_domain = "." SITE_DOMAIN_NAME
...
This line  "." SITE_DOMAIN_NAME  is equal to ".mysite.com"

And in Bootstrap.php wee initialize session.
*** application/Bootstrap.php ***
...
protected function _initSession()
{
$localCfg = new Zend_Config($this->getOption('local'), true);
Zend_Session::setOptions($localCfg->session->toArray());
Zend_Session::start();
}
...

Комментариев нет:

Отправить комментарий