Do AJAX requests retain PHP Session info? - php

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?

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.
From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.

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)

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).

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).
PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)
In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:
If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).
If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)
From OWASP.org:
Effectively, the web application can use both mechanisms, cookies or
URL parameters, or even switch from one to the other (automatic URL
rewriting) if certain conditions are met (for example, the existence
of web clients without cookies support or when cookies are not
accepted due to user privacy concerns).
From a Ruby-forum post:
When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you
use or allow URL-based php sessions, you'll have to add the session id
to every Ajax request url.

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?

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.

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!

put your session() auth in all server side pages accepting an ajax request:
if(require_once("auth.php")) {
//run json code
}
// do nothing otherwise
that's about the only way I've ever done it.

Related

Can an exterior javascript make ajax calls to fetch session data?

Imagine a scenario where you own mysite.com, and it loads javascript from an exterior domain such as adsprovider.com/ads.js.
Can adsprovider.com's javascript then perform an ajax call to mysite.com and attempt to retrieve the user's session data? If so, how can you protect your users against it?
Can adsprovider.com's javascript then perform an ajax call to mysite.com
Yes. The origin is defined by the URL of the HTML document the script is loaded into, not by the URL the script itself is loaded from.
retrieve the user's session data
Only if the session data is exposed through HTTP. Stuff you never give to the client is safe (but there is probably going to be quite a lot of session data that should be kept private between your server and the user).
Note that the script can read document.cookies and steal the session token too (unless the session token is sent with the httponly flag on).
If so, how can you protect your users against it?
Sandbox the adverts in iframes hosted on different origins.
Fortunatly, an Ajax call for your session data can't be directly request from external server.
You can load javascript from a CDN external source of course, but the script run from your own domain, and access to your server is not possible from outside.
Otherwise there would be a lot of security problem.
Also keep in mind that javascript is client side.
You can check Same-origin policy and CORS for more info on this topic.

PHP session VS PHP cookie [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP session or cookie
We are developing a new project where we want to keep track of some information regarding the user from page to page, in terms of security, reliability and server usage is it better to do so with sessions or with cookies? What are the ups and downs of using one method or another.
For example to keep track if the user has successfully logged in or not, or to keep track of the language that the user selected.
Basically we want to know how to decide if we should use cookies or sessions, obviously if we want to keep track of data occurring within different visits to the page in different occasions and even different days the answer would be to use a cookie, but what about keeping track within the navigation of the page without closing the browser.
Thanks
A cookie is a small piece of text that is sent by the server to the client in the HTTP response headers. The client will store it locally and return it back to the server with every request in the request headers. That allows the implementation of some state in the otherwise stateless HTTP protocol.
A session is a concept typically implemented on top of cookies. The server sends a meaningless, unique session token (a random id) as a cookie to the client and the client returns it on every request. Server-side this id is associated with some data. Every time a client sends its session token back to the server in a request, the server looks up the data associated with that token.
The transfer of the session id back and forth between the client and the server can also happen by embedding the session id into all URLs or form requests, it doesn't have to be cookies. Embedding session ids in the URL is a bad idea though, since that allows accidental session transfers if URLs are shared between different users (see below). These days sessions are typically implemented using cookies client-side.
Conceptually cookies and sessions are extremely similar, they both implement state in HTTP. The difference is that a cookie can only store a small amount of data which is transferred back and forth on every request and is editable by the user (because it's information stored on the client); while a session stores all data server-side and is thereby only limited by the server's resources. The only vulnerability sessions have is that if a user can guess or steal the session id of another user, he can impersonate that user. That's known as session hijacking. Plain cookies have no security whatsoever and should not be used for anything important (as in, the user can see and edit the contents, so storing userloggedin=yes in a cookie is the worst thing you can do).

What application component in a LAMP stack, sets the "Set-Cookie" header

The application I'm working with accepts three different types of login. Automatically if the client connects from certain IP-adresses, or a POST request, either from a normal browser rendered form, or towards a JSON reading API-endpoint.
All three options boil down to calling the same functions for registering the user as logged in, and generating a session.
Despite the code paths being the same as far as I can determine, two of these consistently work, while one consistently fails to add a 'Set-Cookie' header to the response, even though the application logic generates a sessionid that gets sent in the reponse body.
Never having needed to dig into how session authentication works to this level of detail, I realise I don't understand. where the 'Set-Cookie' header, should come from. Should application logic always build the header manually? Will PHP do it automatically once session_start() is called? Does Apache do it based on other parts of the header?
I sort of ruled out 1 by failing to find anything with grep -ri "set.cookie" * in the codebase I'm working with.
session_start sends a session cache limiter and a session cookie (or sets a $_GET key with your PHPSESSID).
This function is where the Set-Cookie paramater is sent from. Apache will then pass it back to the browser when it sends the page back.
You need to remember however that storing the cookie is actually up to the browser. By and large they will be set without issue, but certain conditions will stop this from happening, such as the security settings in Internet Explorer or the user rejecting cookies entirely.
Further reading:
http://www.php.net/manual/en/function.session-start.php
http://www.php.net/manual/en/function.session-get-cookie-params.php
http://www.php.net/manual/en/function.session-status.php

PHP accessing cookies from other domain with user explicit authorization

I'm coding a php framework to add functionalities for a second party website, which is not ours and don't have control at all.
This website has Oauth 2.0 authorization for its clients and save access token in cookies. As I must interact with their own public API, I need to read that token to make my requests.
Question is.. which is the best strategy to code that? I'm not a php programmer but very proficient in C++. I wonder if its possible to open website inside an IFRAME and read cookies with javascript, am I making any sense????
If you really want to do that, open the site in a hidden iframe, the page that the iframe loads should have something like
window.parent.getCookie(/* the cookie value*/);
So you can use the getCookie method is in your main site and read the external site cookie, then you can use ajax to send the cookie value to your script, and work with it or save it as a cookie, you can also use javascript to save the cookie.
EDIT: Remember cookies should never store sensitive data, even in your own site.

When to use URL/session/cookie variables?

I do a lot of php and javascript, but I think this is relatively language-agnostic question. Are there any best-practices for when to use each of:
URL variables
SESSION variables
cookies
I understand the inherent limitations of what some of them can't do, but it seems like their use can overlap sometimes, too, and those instances are what I'm really asking about.
EDIT
Just to clarify: I'm pretty familiar with the technicalities of which method is stored where, and which the client/server can access. What I am looking for is something a little higher-level, like "temporary user settings should live in cookies, data state info should live on the server, etc..."
Thanks!
In general:
Use URL (GET) parameters for sending simple request parameters to the server, eg. a search query or the page number in a product listing.
Use session variables, as the name indicates, to store temporary data associated with a specific user session, eg. a logged-in user's ID or a non-persistent shopping cart.
Avoid using cookies when possible. Use them sparingly to store settings that are tied to a particular computer / user profile, eg. a setting such as "remember my user ID on this computer".
Sessions are stored on the server, which means clients do not have access to the information you store about them. Session data, being stored on your server, does not need to be transmitted in full with each page; clients just need to send an ID and the data is loaded from the server.
On the other hand, Cookies are stored on the client. They can be made durable for a long time and would allow you to work more smoothly when you have a cluster of web servers. However unlike Sessions, data stored in Cookies is transmitted in full with each page request. You should use cookie if you need longer logged-in sessions.
URL variables (GET) are open and can be seen by user. They are also useful as it allows the user to bookmark the page and share the link.
PHP embeds the session id directly into URLs when cookies are disabled. Then, the session id becomes a value accessible thru an HTTP GET variable.

Categories