1

I have 2 php files, in the first file:

    <?php
        session_start();    
.
.
.
        $_SESSION['favcolor'] = "green";
        echo "ses: ".$_SESSION['favcolor'];
    ?>

and in the second file:

<?php
    session_start();
    echo "ses: ".$_SESSION['favcolor'];
?>

When executing the first page, i do see the correct favcolor but when executing the second page in the same browser, I get {"error":"Undefined index: favcolor"}. I know I need to check the existence of this key before using it but I was wondering why it's not there in the first place because this is what I want to achieve, the store/restore a session value between PHP calls. What am I missing?

Amos
  • 1,321
  • 2
  • 23
  • 44
  • 1
    Sure that there's no output before `$_SESSION['favcolor'] = "green";`? – u_mulder Jul 05 '15 at 14:43
  • 1
    This is an interesting issue. I suggest three debugging things: 1) Echo your session id `session_id();` Not sure wether it returns or echo it. 2) Open file1 via browser, delete `$_SESSION['favcolor'] = "green";` and open file1 again. 3) Check if there is a function like "isSessionStarted" and add it in both files. – Alexander Jul 05 '15 at 14:51
  • 1. echoing the session id in both files, I get 2 different ids. 2. how to delete the $_SESSION['favcolor'] = "green"? not sure I understand. 3. I don't have isSessionStarted but if I have session ID, I guess it is started? – Amos Jul 05 '15 at 15:01
  • u-mulder, what do you mean by sure there's no output before $_SESSION['favcolor'] = "green";? the first output is after setting this value, now I added the session id just before that – Amos Jul 05 '15 at 15:13
  • 1
    Turn on error reporting and display errors on screen: `error_reporting(E_ALL); ini_set('display_errors', 1);` always when developing and testing code, placed at the very _top_ of both scripts. The whitespace before ` – Michael Berkowski Jul 05 '15 at 15:41
  • It could possibly be a http:// versus https:// thing, so make sure you are using the same protocol when accessing both pages. (Normally you would get the same session ID, but I think that can be configured to work differently.) – Anders Jul 05 '15 at 19:03
  • I added error_reporting(E_ALL); ini_set('display_errors', 1); but nothing new showed up. while working in the same tab (f5), it does show the same session id but the session id is different between the 2 tabs. If I take the URL from tab2 and run it in tab1, the session id is of tab2. – Amos Jul 06 '15 at 09:04
  • The problem was that on tab1 i did domain.com/page1.php.... and on the other tab it was www.domain.com/page2.php.... the www difference caused the problem... – Amos Jul 06 '15 at 12:20

0 Answers0