22 Votes

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

Tip by Stefan Trost | Last update on 2021-05-19 | Created on 2012-12-04

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 but only under www.example.com.

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

The Solution

I want to show you two solutions for this problem. Both approaches 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 (that means you have to set the parameters again before each new setting of variables in another script).

The first parameter (lifetime) is irrelevant for us, so we pass the default value which is 0 (until the browser is closed). 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 in the same way like in the first approach.

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.