开发者

Can a script called by XHR reference $_COOKIE?

开发者 https://www.devze.com 2022-12-26 03:46 出处:网络
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

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

精彩评论

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