tags:

views:

2355

answers:

7

If I had a user logged onto my site, having his id stored in $_SESSION, and from his browser he clicked a 'Save' button which would make an AJAX request to the server. Will his $_SESSION and cookies be retained in this request, and can I safely rely on the id being present in the $_SESSION?

+3  A: 

If the PHP file the AJAX requests has a session_start() the session info will be retained. (baring the requests are within the same domain)

Ólafur Waage
+7  A: 

What you're really getting at is: are cookies sent to with the AJAX request? Assuming the AJAX request is to the same domain (or within the domain constraints of the cookie), the answer is yes. So AJAX requests back to the same server do retain the same session info (assuming the called scripts issue a session_start() as per any other PHP script wanting access to session information).

cletus
I might be wrong, but I thought it wasn't even possible to post ajax requests to other domains (subdomains excluded)?
Emil H
You might be able to cheat with the dynamic script trick. Never tired it though.
cletus
Yes, ajax requests can't be made to other domains. However you can dynamically insert a <script> tag into the page and set its src to an off-domain url that echoes out the javascript.
Click Upvote
+1  A: 

It is very important that AJAX requests retain session. The easiest example is when you try to do an AJAX request for the admin panel, let's say. Of course that you will protect the page that you make the request to, not to accessible by others who don't have the session you get after administrator login. Makes sense?

Bogdan Constantinescu
+7  A: 

The answer is yes:

Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way.

thomasrutter
A: 

One thing to watch out for though, particularly if you are using a framework, is to check if the application is regenerating session ids between requests - anything that depends explicitly on the session id will run into problems, although obviously the rest of the data in the session will unaffected.

If the application is regenerating session ids like this then you can end up with a situation where an ajax request in effect invalidates / replaces the session id in the requesting page.

John
A: 

That's what frameworks do, e.g. if you initialize session in Front Controller or boostrap script, you won't have to care about it's initalization either for page controllers or ajax controllers. PHP frameworks are not a panacea, but they do so many useful things like this!

PHP thinker
A: 

But I have a problem that the sessions which I have created during ajax request are not accessible in PHP site.

Arsalan