开发者

Can a script called by XHR reference $_COOKIE?

Quick yes/no - I'm building an AJAX application and some scripts require authentication. Can I read开发者_如何学编程 $_COOKIE['username'] and $_COOKIE['password'] on the server if the PHP script was called via XHR, whether that be $.get() or $.post()?

Side question: Can it also set cookies? Is that considered "good practice"?


Cookies are sent in the headers of HTTP requests. No matter what kind of request, (ie. GET/POST/etc.), as long as it is using the HTTP protocol (or HTTPS), then the cookie headers can be used. This is a two-way street... cookies are sent in the headers to the server (Cookie: header), and the server sets cookies in the headers (Set-Cookie: header).

This means that Ajax/XHR requests are fine, as they are at the core simply HTTP requests. Modern browsers will all send cookies along with their Ajax requests, and honor any incoming cookies as a result. This means that for your receiving PHP script, $_COOKIE will contain cookies as normal if any were available.


Yes. They will come in via the HTTP request headers for all requests matching the cookie's domain.

You can rely upon the PHP session and cookie variables for these requests.

You can set cookies as well (we do this with an Ajax login form on our site). I don't think there's any problem with it, either technically or philosophically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜