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,
$_COOKIEwill contain cookies as normal if any were available.