Samuel Andersson
Samuel Andersson

Reputation: 33

PHP Sessions through subdomains when not allowed to edit php.ini

My host (one) is not allowing me to change the php.ini file and nor can I find it (I probably don't have read access to it even). When I am trying to make session variables go across subdomains I can't since the session cookie is set for the main domain only (example.com). I would like it to be set for .example.com

I have tried to set the php ini file to allow this.

ini_set('session.cookie_domain', '.example.com');

That did not work because I am not allowed to run the ini_set() function. I also tried finding the php.ini file but could not find it in my FTP client. Using phpinfo() wields me it is in /etc/php but I don't have access to that directory.

I expect this to work but clearly it does not. Checking the developer console in Firefox the domain path for the PHPSESSID cookie is still example.com and not .example.com

Is there any workaround other than setting the session variables on the correct subdomain from the start?

Upvotes: 0

Views: 214

Answers (3)

ttrasn
ttrasn

Reputation: 4826

You can set ini variable like this before session_start()

ini_set('session.cookie_domain', '.example.com' );

or for that question you can set in htaccess file like this:

php_value session.cookie_domain .example.com

and from this answer:

    if(isset($_COOKIE['session_id']))
        session_id($_COOKIE['session_id']);
    Zend_Session::start(); //or session_start();
    if(!isset($_COOKIE['session_id']))
        setcookie('session_id', session_id(), 0, '/', '.yourdomain.com');

at the end if any of this ways doesn't work, you can change the session_name

 session_name('example_name');

then use the following code into the php page

session_set_cookie_params(0,"/",".example.com",FALSE,FALSE);
setcookie(session_name(), session_id(),0,"/","example.com");
session_start();

for more information see this question

Upvotes: 0

Soren
Soren

Reputation: 260

This is not the best solution !

Regarding your situation and if you cannot set it using .htaccess, you can make a redirect to your subdomain(s), create the session and redirect back to the URL where you want to be,

EX : example.com -> any action -> go to sub1.example.com -> create session -> go to sub2.example.com -> create session -> ... -> go to example.com

Or : You can also create pixel image with links to your subdomains if you don't want to use redirect

For this two solutions to work, you need to set sessions separately for each subdomain.

Upvotes: 0

Álvaro González
Álvaro González

Reputation: 146380

Session cookie params can also be set with session_set_cookie_params(). The domain is the third argument.

Upvotes: 1

Related Questions