0

Ok here is my problem: When a user logs into my site I put all their user info into a session like this

session_start();
//Put all user info into session cookie
$_SESSION["login"] = 'true';
$_SESSION["id"] = $user_info['id'];
$_SESSION["firstname"] = $user_info['firstname'];
$_SESSION["lastname"] = $user_info['lastname'];
$_SESSION["screen_name"] = $user_info['screen_name'];
$_SESSION["facebook"] = $user_info['facebook'];
$_SESSION["email"] = $user_info['email'];
$_SESSION["date_joined"] = $user_info['date_joined'];
$_SESSION["account_type"] = $user_info['account_type'];
$_SESSION["account_active"] = $user_info['account_active'];
$_SESSION["hashed_password"] = $user_info['hashed_password'];

The problem is if they logged in from www.domain.com and then end up on a page at domain.com or the other way around they login from domain.com and end up on a page at www.domain.com the info stored in the session is not available.

How can I have the session info available no matter if they logged in with www or not?

@ Mr. Grossman

Would it be proper to do something like this:

    <?php
    //Ok I modified the code so I don't get the undefined errors I was getting

//OLD CODE
    //$currentCookieParams = session_get_cookie_params(); 
    //$rootDomain = '.domain.com'; 
    //session_set_cookie_params( 
        //$currentCookieParams["3600"], 
        //$currentCookieParams["/"], 
        //$rootDomain, 
        //$currentCookieParams["false"], 
        //$currentCookieParams["false"] 
    //); 

    //session_name('mysessionname'); 

//NEW CODE
    $rootDomain = '.beckerfamily1.com'; 
    session_set_cookie_params( 3600, '/', $rootDomain, false, false); 
    session_start();

    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 2700)) {
        // last request was more than 45 min ago
        if(isset($_SESSION['id'])){
        $connection = mysql_connect('localhost', '******', '*******');
        if (!$connection){
            die('Database connection failed: ' . mysql_error());
            }
        $db_select = mysql_select_db('beckerfamily');
            if(!$db_select){
                die('Could not select database: ' . mysql_error());
                }
        $query = "UPDATE users SET online='no' WHERE id='{$_SESSION['id']}' LIMIT 1";
        $result = mysql_query($query);
        if (!$result) {
                die("Database query failed: " . mysql_error());
            }
        }
            $_SESSION = array();
            if(isset($_COOKIE[session_name()])) {
                setcookie(session_name(), '', time()-42000, '/');
            }
        session_destroy();   // destroy session data in storage
        session_unset();     // unset $_SESSION variable for the runtime
        if(isset($connection)){
            mysql_close($connection);
            }
     }
    $_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
    ?>

Also is it necessary to have session_name('mysessionname'); or can I just omit that and PHP will set the session name on its own?

David
  • 11
  • 4
  • possible duplicate of [Session cookie and www.](http://stackoverflow.com/questions/5312188/session-cookie-and-www) – Dan Grossman Jul 27 '11 at 02:09
  • possible duplicate of [Allow php sessions to carry over to subdomains?](http://stackoverflow.com/questions/644920/allow-php-sessions-to-carry-over-to-subdomains) – Dan Grossman Jul 27 '11 at 02:09
  • Yes, that's what you do, but you put your real domain where it says `domain.com`. Don't remove the leading period, that's important. – Dan Grossman Jul 27 '11 at 02:52
  • Got this error when trying to run that code:Notice: Undefined index: 3600 in J:\www\www.beckerfamily1.com\testing\login.php on line 5. I thought maybe I needed to remove the quotes but still didn't work. – David Jul 27 '11 at 03:07
  • I fixed the code so I am not getting the errors anymore but unfortunately it didn't solve my original problem of the session info not being available weather the user was using www in the url. – David Jul 27 '11 at 03:49
  • Never-mind my last comment. I must have had the pages cached it is working perfectly now. Thanks to Mr. Grossman I would've never figured it out without your help. – David Jul 27 '11 at 03:59
  • Please click the checkmark graphic next to my answer when you can. I'm glad you fixed it. – Dan Grossman Jul 27 '11 at 04:04
  • I do have one more question before I leave this post. I know that sessions normally have to be the very first thing after the opening PHP tag but is it possible to make this code reusable on any site? I was thinking I could use a constant for $rootDomain but then I would have to require my constants before I start the session which would break the sessions must be always be first rule. Any suggestions? – David Jul 27 '11 at 05:03
  • Starting the session doesn't have to be the first code you execute, it has to be the first output of your code, because starting a session means sending a cookie, and sending a cookie happens in an HTTP header, and HTTP headers come before the HTTP response body. You can have as much code as you want before you call `session_start()`, you just can't send any output. – Dan Grossman Jul 27 '11 at 05:09
  • It worked perfectly loading my constants and then the session stuff. This will save me a ton of work in the future. Thanks Again! – David Jul 27 '11 at 06:42

2 Answers2

1

Cookies (like the PHPSESSID cookie) are only available on the domain they were set on. You can make the domain include all subdomains:

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

or if configuration does not allow you to override that,

$currentCookieParams = session_get_cookie_params(); 

$rootDomain = '.example.com'; 

session_set_cookie_params( 
    $currentCookieParams["lifetime"], 
    $currentCookieParams["path"], 
    $rootDomain, 
    $currentCookieParams["secure"], 
    $currentCookieParams["httponly"] 
); 

session_name('mysessionname'); 
session_start(); 

http://php.net/manual/en/function.session-set-cookie-params.php

Even better might be to choose whether you want your site accessed through www or not, and redirect all requests to the other.

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • 3
    What a mind-boggling question. Why would I write it as answer to your question if I didn't think it'd work? – Dan Grossman Jul 27 '11 at 02:22
  • 1
    sorry this website didn't let me finish what I was going to write. I was trying to post a block of code after my will this work question. This is frustrating I am trying to put a block of code but it says I have too many characters. – David Jul 27 '11 at 02:31
  • @Dan Perhaps he thought the answer was posted by evil Dan. You know, the one with the goatee – Phil Jul 27 '11 at 02:33
  • @David Don't post code in comments. Edit your question instead – Phil Jul 27 '11 at 02:34
0

I'm not sure what language you are using, but you need to change the "domain" property of your session cookie. If you set the cookie domain to "domain.com", it will be accessible on both "domain.com" and "www.domain.com".

David
  • 34,223
  • 3
  • 62
  • 80