8

I set my session like so in my PHP code : $_SESSION['user_id'] = $login; and this seems to work fine whilst uploaded to my server and carries across different pages, however when I am testing the website on my local machine the session seems to become immediately unset after leaving the script where it is set.

I am testing on my local machine using XAMPP and exactly the same code.

I am not sure why this problem is occurring and would greatly appreciate any helpful answer.

Example that is not working:

$_SESSION['user_id'] = $login;
echo '<META HTTP-EQUIV="refresh" content="0;URL=../home.php">';  

EDIT 1:

Here is my entire function in which I log in (it's part of the class):

public function loggingIn(){
    session_start();

    $db = new Database('localhost','root','','userdata');
    $userFunctions = new Users($db);

    $username = $_POST['usernameInput'];
    $password = $_POST['passwordInput'];

    if(empty($username) || empty($password)){
        $this->errors['u&p'] = 'Please Enter Your Username AND Password';
        $this->printE();
    } elseif($userFunctions->user_exists($username)===false){
        $this->errors['nm'] = 'That Username/Password Combination Is Not Valid';
        $this->printE();
    } else {
            $login = $userFunctions->login($username, $password);

    if($login === false){
            $this->errors['nm'] = 'That Username/Password Combination Is Not Valid';
            echo 'Login Failed!';
        } else  {
           if(!$userFunctions->economyTableExistsForUser($login)){
               $userFunctions->createEconomyTableForUser($login);   
           }
           if(!$userFunctions->schoolTableExistsForUser($login)) {
               $userFunctions->createSchoolTableForUser($login);    
           }

               $_SESSION['user_id'] = $login;

               echo $_SESSION['user_id'];  // working fine

               header('Location: ../home.php');
        }
    }   
}
Ilia Ross
  • 13,086
  • 11
  • 53
  • 88
Josh Jackson
  • 119
  • 1
  • 2
  • 9

11 Answers11

11

Let's guess that your home machine is not having:

session.autostart = On

in your php.ini, while your other machine obviously is.

Make sure that you have set in your PHP code:

session_start();

PHP: session_start - Manual

If you don't, then your session is not started, unless my first conjecture is true.

Besides, you must check for you PHP version on your localhost and settings in php.ini. Make sure that the directory where you store you session files is writeable and session files do really exist.

EDIT 1:

You better use PHP solution for redirection:

header("Location: /");
exit();

EDIT 2:

PHP has functions that modify HTTP headers. Some of them:

EDIT 3:

Line-breaks and spaces could be a problem but there are also invisible character sequences which can cause Warning: Cannot modify header information, like the UTF-8 BOM (Byte-Order-Mark). Try re-saving your file making sure that it's saved just as UTF-8 (no BOM).

EDIT 4:

To properly debug your code make sure that PHP displays all warning and notices. Run it before session start:

ini_set('display_errors', -1);

EDIT 5:

You must also check session.gc_maxlifetime setting:

session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

EDIT 6:

To view white-spaces in Sublime Text, edit the settings:

// Set to "none" to turn off drawing white space, "selection" to draw only the
// white space within the selection, and "all" to draw all white space
"draw_white_space": "selection",

You can set it in Preferences->Settings Default. If you edit your user settings Preferences->Settings - User and add the line as per below:

{
    "font_size": 10,
    "draw_white_space": "all"
}

Also make sure it shows all other special characters to properly debug your code!

EDIT 7:

Finally try adding session_write_close(); right before redirecting.

EDIT 8:

Set in your PHP file, before session_start();, session.save_path = "/home/username/tmp"; directive. Create tmp dir outside of public_html. Make sure that tmp dir has chmod 770 and created with the same user/group privileges . Run ls -lsa in your home dir to check if the new directory has the same user/group as other directories, like public_html for instance. If not, make sure changing permissions as root on tmp by running chown username:groupname /home/username/tmp.

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88
  • I do in fact do this, sorry I didn't mention it. I have now included it in the original post. – Josh Jackson Oct 28 '13 at 20:42
  • Ah now doing that produces and error on my server saying something along the lines of "PHP Headers already sent"... this is why I used this form of redirection. – Josh Jackson Oct 28 '13 at 20:54
  • Okay so I have tried header to redirect and the session variable still doesn't seem to carry across the page. Also this is the only real bit I can see helping. I try echoing it in the script right after I set it and it works so it is definitely getting set. – Josh Jackson Oct 28 '13 at 21:13
  • It echos the user_id retrieved from a database, this works on my server and also works on localhost, as I mentioned the variable is definitely getting set – Josh Jackson Oct 28 '13 at 21:20
  • I use Sublime text editor, also the session.gc_maxlifetime is set at 24 minutes – Josh Jackson Oct 28 '13 at 21:32
  • I have edited my answer to include the entire method in which I log in, thanks for your help I appreciate it. – Josh Jackson Oct 28 '13 at 21:38
  • Yes it is part of a class, just to throw it out there is it possible that the header is redirecting before the session variable has a chance to set, this could be why it works on the same page? – Josh Jackson Oct 28 '13 at 21:50
  • No I added session_write_close(); just before I redirect and it does not seem to do anything – Josh Jackson Oct 28 '13 at 21:54
  • This doesn't seem to have any effect – Josh Jackson Oct 28 '13 at 21:59
  • Okay thanks for all of your help , I will try that , and talk to you tomorrow too! – Josh Jackson Oct 28 '13 at 22:02
  • Just as a note, I tried it with a simple PHP file, just setting the variable, redirecting then trying to print it out however it still does not carry over. – Josh Jackson Oct 28 '13 at 22:06
  • Then you must check for you PHP version on your localhost and settings in php.ini. Make sure that the directory where you store you session files is writeable and session files do really exist. You shouldn't add what you have forgotten at the very beginning in your answer, meaning *session_start();* as it makes unclear my answer. Change it to edits please, so it would be clear. – Ilia Ross Oct 29 '13 at 07:38
  • Okay I included the edit thing and also I am running PHP 5.3.8 on both my local machine and my server. – Josh Jackson Oct 29 '13 at 09:16
  • Do what I written in *EDIT 8* please! It's definitely there! There is no other reason for that! And please let's remove so many comments! They ask kindly to move it to chat! – Ilia Ross Oct 29 '13 at 09:36
  • Josh, was there any of luck? – Ilia Ross Oct 30 '13 at 07:55
  • @Carpetsmoker Yes, totally agree and now I'm aware about this for sure. Fixed it. I read your answer, nice. Thanks. – Ilia Ross Mar 13 '16 at 06:52
  • session.autostart = On did the trick on xampp in mac environment. – Harish Lalwani Sep 20 '19 at 08:04
4

A quick update on this. I found this response very useful, however, please note that in my installation of XAMPP, the php.ini entry for session.autostart=On, is slightly different. I found the following:

; Initialize session on request startup. ; http://php.net/session.auto-start session.auto_start=0

I changed this to:

; Initialize session on request startup. ; http://php.net/session.auto-start session.auto_start=1

2

Make sure session cookies are enabled in php.ini (xamp\php\php.ini).

session.use_cookies=1
theDmi
  • 17,546
  • 6
  • 71
  • 138
jsHate
  • 499
  • 1
  • 3
  • 20
1

In your php.ini check:

  1. variables_order contains the letter S
  2. Check that session.save_path exists and is writeable by the user under which PHP is running.
Sammitch
  • 30,782
  • 7
  • 50
  • 77
1

If you are using PHP embedded within .htm/.html documents, you need to ensure that Apache can process them appropriately. This is done by editing the httpd.conf and adding the line

AddType application/x-httpd-php .html .htm

to the section <IfModule mime_module>

LJT
  • 1,250
  • 3
  • 20
  • 25
1

I was fighting with this problem but solve...

In your /opt/lampp/etc/php.ini try to change this line:

session.save_path = "/var/lib/php/session"

For this:

session.save_path = "/opt/lampp/var/session"

Note: Maybe you need to create the folder "session" in /opt/lampp/var

miken32
  • 42,008
  • 16
  • 111
  • 154
davidleosam
  • 344
  • 3
  • 4
1
  1. Open php.ini
  2. change session.auto_start with "1"
  3. "Stop" Apache if running
  4. "Save" php.ini
  5. "Start" Apache
0
Session Issue Fixed in Xampp 7.1.6 with following Changes in php.ini
Line #1403 set: 
session.auto_start = 1    
0

I had similar problems live site working Xampp not.

The trick in my case was to disable the two lines below.

header('Set-Cookie: same-site-cookie=huis; SameSite=Lax');
header('Set-Cookie: cross-site-cookie=stijl; SameSite=None; Secure');

So check anything that modifies something regarding coockies is my advise.

Henry
  • 1,242
  • 1
  • 12
  • 10
0

Please check your "session.cookie_path" in php ini. By default it is "session.cookie_path=/"

-1

Enable session cookies in php.ini (C:\xamp\php\php.ini).

CHANGE

session.use_cookies=0

TO

session.use_cookies=1

AND remember to restart xampp

justice
  • 75
  • 1
  • 2
  • 11