Brian Moreno
Brian Moreno

Reputation: 1027

PHP Session Only Works On Some Pages

this is kinda weird. Ok so I'm working with a session to know when the user has logged in. When the user logs in a session gets created.

The problem i'm having is the session isn't working on some pages. When I do a var_dump($_SESSION['u_up']); on my index page it show the session: array(1) { ["u_up"]=> string(7) "example" } but when I make an Ajax call to another script and do the same var_dump($_SESSION['u_up']); it returns an empty array: array(0){}.

Does anyone know why this is happening? I have session_start() on top on both files but somehow my second script won't pick up on my sessions. Any help is greatly appreciated!

This is my simple Ajax script:

//Update to not view tutorial           
$.ajax({
    type: "POST",
    url: 'http://192.168.1.75/php/script.php',
    success: function(data){
        console.log(data);
    }
});

Upvotes: 1

Views: 58

Answers (2)

Vulkhan
Vulkhan

Reputation: 458

You are doing a cross domain request, 192.168.1.75 and localhost are not considered the same domains and do not share cookies.

For safety reasons cross domain requests does not include cookies. If you don't send the phpsessid cookie you won't be able to retrieve your old php session, which will make your session empty.

Beside this i strongly suggest you to use relative path to avoir such issues in the futur.

$.ajax({
    type: "POST",
    url: '/php/script.php',
    success: function(data){
        console.log(data);
    }
});

Upvotes: 2

Brian Moreno
Brian Moreno

Reputation: 1027

Ok so it turns out I had to change the url in the Ajax request to localhost. So it ended up looking like this:

//Update to not view tutorial           
$.ajax({
    type: "POST",
    url: 'http://localhost/php/script.php',
    success: function(data){
        console.log(data);
    }
});

Don't really know why i have to specify localhost instead of being able to specify my computer's ip.

Upvotes: 0

Related Questions