Search code examples
phpsessionsession-cookiessession-variables

Session variable unavailable in ajax handler ( php script )


My directory structure looks like below:

public_html
    |_ ajax
        |_ test_handler.php
    |_ test.php

My test.php looks like this:

session_start();
if(isset($_SESSION["tested"]) && $_SESSION["tested"] == "NO"){
    //unset the session array and destroy current session
    destroyActiveSession();

    //start a new session
    session_start();

    $_SESSION["test_var"] = "Hello world!"
    $_SESSION["tested"] = "YES"
}

test_handler.php has following code(simplified):

session_start();
exit($_SESSION["test_var"]);

Using local environment(XAMPP) and executing on google crome

In test.php page $_SESSION["test_var"] works fine but in test_handler.php I'm getting Undefined index: test_var error. What am I doing wrong???


Solution

  • So if anyone ran into this problem, here's what solved my problem: New test.php:

    session_start();
    if(isset($_SESSION["tested"]) && $_SESSION["tested"] == "NO"){
    
        //unset the session array 
        $_SESSION = array();
    
        $_SESSION["test_var"] = "Hello world!"
        $_SESSION["tested"] = "YES"
    }
    

    And new test_handler.php :

    <?php
        session_start();
        exit( $_SESSION["test_var"] );
    ?>