سؤال

I have a login.php in the root directory. On valid user login, it executes the following code :

function log_in($id,$keep_login)
{
$_SESSION['auth'] = true;
$_SESSION['id'] = $id;
if($keep_login==TRUE) {
    setcookie(session_name(),session_id(),time()+LOGGED_IN_TIME);
}
}

On login.php, in the starting, after including header file (header file contains session_start on first line), I check if a user is logged in using this function :

function logged_in()
{
if(!isset($_SESSION['auth'])||empty($_SESSION['auth'])||!isset($_SESSION['id'])||empty($_SESSION['id']))
{
    return false;
}
return true;
}

And if the user is already logged in, I redirect them to profile.php using :

if(logged_in())
{
    header('Location: profile.php');
}

I have another file enter.php in /sources/enter.php

The login data from login.php is sent to enter.php . However, in enter.php , I see that the user is already logged in. i.e. logged_in() returns true. Curious about this, I echoed the session id on both login.php and enter.php , and the ids were different.

BTW, I include the header file like this : $included=TRUE; require_once 'sources/headers.php';

Does the initialization of $included before session_start (session is started in headers.php) interfere with the session?

Although I AM logged_in, somehow my login.php cannot access my session. Can someone point the problem to me?

UPDATE : when I move enter.php to the root directory (same as login.php), it works like it should. Although for security reasons, I want to move it to /sources/enter.php . Any solution?

ANOTHER UPDATE : just came to know that when I move the enter.php to the root directory, the files in any subdirectory cannot access the session. The session variables are there, but the session id is different.

AND ONE MORE UPDATE : I just discovered, that the session id in the subdirectories is another id, and contains different $_SESSION variables. What I mean, that root directory has $_SESSION['id']=1 and the subdirectories have $_SESSION['id']=4. Maybe this is because the session id's are different.

هل كانت مفيدة؟

المحلول

Any output by the server before session_start() will interfere and cause your session to fail.

I'm not sure if that's your case but you should add session_start() as the first thing written in your config file. Make sure it's the first thing ever executed on a page.

Sometimes session_start() gets rekt if your file encoding is not utf8-without-bom (you should be using that at all times).

نصائح أخرى

I finally found the problem. It was not in the script. When I used another browser, it worked perfectly. Then i thought that Chrome must have preserved the old session cookie, and was still using it when in the subdirectory. I cleared cache, and it now works. Huh! Such a simple answer it was, I still need to learn. Thanks guys for helping me out!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top