11 Vote

PHP: Make PHP session variables (PHPSESSID) also available under subdomains

Tip by Stefan Trost | 2012-12-04 at 16:48

When using PHP session variables, there is the disadvantage that the variables are not automatically available under all sub-domains. In this tip, I will show you how you can avoid this by overwriting the default PHP parameters to make PHP session variables also readable under subdomains.

The Problem

If we are using on www.example.com the code

session_start();
$_SESSION['var'] = 1;

in order to start a session and to set session variables, the session variable will not be available under sub.example.com.

The reason: The default values of session_start() set the session in a way that it is available only for the current path and for the current domain. So, in our example, for "www.example.com", but not for "sub.example.com".

The Solution

I want to show you two solutions for this problem. Both overwrite the default settings and make it possible to use the session cookie also under subdomains.

Approach 1

session_set_cookie_params(0, "/", ".example.com");
session_start();
$_SESSION['var'] = 1;

The function session_set_cookie_params() allows adjusting the cookie parameters from php.ini for the duration of the current script. The second parameter is the path, the third parameter the domain. Because we write a dot before the domain, our session variable next to www.example.com is also available on all subdomains such as sub.example.com or en.example.com, regardless, under which domain we start the session.

Approach 2

ini_set('session.cookie_path', '/');
ini_set('session.cookie_domain', '.example.com');
session_start();
$_SESSION['var'] = 1;

Alternatively you can also use ini_set(). Here we change the options "session.cookie_path" and "session.cookie_domain" for the duration of the current script.

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.