Getting session variables to work with http:// AND www.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Getting session variables to work with http:// AND www.

Post by Citizen »

I remember dealing with this a long time ago, but cant find the solution by searching the forums or google....

How can we get a session variable to work on both:

http://page.com
and
http://www.page.com
JacobT
Forum Commoner
Posts: 43
Joined: Tue May 13, 2008 11:07 am
Location: Los Angeles, CA

Re: Getting session variables to work with http:// AND www.

Post by JacobT »

I'm sure there's probably a cross-subdomain solution, but in my opinion, it's bad to allow people to switch between www and non-www. I would add a .htaccess mod_rewrite rule to force WWW or remove WWW. You can also set a cookie (which can be cross-subdomain compatible) and use that to check/refresh your session.

This is the mod_rewrite code I use:

Code: Select all

RewriteCond %{HTTP_HOST} !^(www\.|$) [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Good Luck!
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Re: Getting session variables to work with http:// AND www.

Post by Citizen »

Thanks, unfortunately, this method wont work in this case since its for a customer that needs this code of mine to work independent of the rest of the sites :(
JacobT
Forum Commoner
Posts: 43
Joined: Tue May 13, 2008 11:07 am
Location: Los Angeles, CA

Re: Getting session variables to work with http:// AND www.

Post by JacobT »

Citizen, can you store the data that's in the session in a DB and then use a cookie to reference it? Then you can set the cookie to be accessible on all subdomains like so:

Code: Select all

setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1);
would that work?
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Re: Getting session variables to work with http:// AND www.

Post by Citizen »

I think I'll try that. Thanks!
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: Getting session variables to work with http:// AND www.

Post by Zoxive »

You can also tell php to set the session cookie the same way.

Code: Select all

<?php
// Very top of file before session_start()
ini_set('session.cookie_domain',".myserver.com");
 
You can also put this in a .htaccess file, or in the php.ini file directly.
Post Reply