Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the session id change when requesting through ajax in php?

Tags:

I'm logged in on Banana.com. Banana has a api link on /app/ajax_loggedin.

My website is Monkey. Monkey runs a simple GET json to banana's /app/ajax_loggedin, which returns a loggedin value either 1 or 0.

Why is it always returning 0 when it's through ajax, even though I really am logged in on Banana and also when accessing the link directly gives me 1. How can the developer at Banana fix it?

I would have understood it if it's a server side call, but I don't understand why it wont tell me if im logged in, if Banana makes the request. Running session_id() check, it generates a new one each call through ajax and when accessing directly it works just fine and keeps the same.

Is there any fix or another way to do this?

like image 470
Karem Avatar asked Jul 01 '15 13:07

Karem


People also ask

Does session id change?

Every time an Internet user visits a specific Web site, a new session ID is assigned. Closing a browser and then reopening and visiting the site again generates a new session ID.

How does PHP generate session id?

The session id is a random value generated when a session is started. The session id is stored as a cookie in the browser such that on subsequent visits the data stored in the session can be loaded and reused. This issue is about the session id (cookie value) and not about the session name (cookie name).

Is PHP session id unique?

PHP allows us to track each visitor via a unique session ID which can be used to correlate data between connections. This id is a random string sent to the user when a session is created and is stored within the user's browser in a cookie (by default called PHPSESSID).

Can we set session in Ajax?

If you have a session started then they exist for all pages in the session - so they aren't sent: you just use them. For AJAX, you can send any values you wish when executing the XMLHttpRequest send() function. Since your using jQUery, you'll need to use their method. I prefer straight javaScript.


1 Answers

Every point of entry or call to the server (APIs) needs to have session_start() at the beginning. If it does not read in the session identifier, it will act as if there wasn't one and then return a new session identifier. When your browser gets the response, it will overwrite the session identifier with the new one. Make sure that you have session_start() at the top of all places where you make a call to the server so that it knows what session to use.

like image 157
Cohan Avatar answered Sep 30 '22 20:09

Cohan