How can PHP see client side cookies?
To elaborate: When working with PHP & Javascript, I understand that PHP gets processed on the server side. While Javascript happens on the client side.
In Javascript I can check and set these client cookies. That makes sense.
However, with PHP, if I check a client cookie value as part of a conditional statement that also sets , how is PHP able to see the clients cookie value while the PHP is happening on the server side?
Here's an example of the PHP conditional that lives in a php file:
<?PHP
if ($_COOKIE["name"] == “Mickey”) {
setcookie(“fulsome”, “Mickey Mouse”, time()+3600);
}
?>
Accessing Cookies with PHP Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example. You can use isset() function to check if a cookie is set or not.
Cookies are always stored in the client. The path only sets restrictions to what remote pages can access said cookies. For example, if you set a cookie with the path "/foo/" then only pages in the directory "/foo/" and subdirectories of "/foo/" can read the cookie.
Cookies ¶ PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.
Cookies can only be read by the website the domain that creates them; you can use sub-domains domains, url paths. Cookies are generally considered insecure if used from the client side, and should not be used to hold sensitive data if accessed from the client side.
There is no such thing as a client side cookie.
A cookie is a piece of data associated with a set of URLs in a browser. Every time the browser makes an HTTP request to one of those URLs, the cookie is included in the Request headers.
They were originally designed to be set via HTTP Response headers.
An API was added to browsers that allows them to be created and set by JavaScript. These are still regular cookies though and will be included in every request to the associated URLs.
It is possible to mark a cookie as http_only
which will cause browsers to prevent access to that cookie from JavaScript. There is no direct equivalent for imposing a similar limit going the other way. The closest you could come to that would be to use something like Local Storage instead of cookies.
how is PHP able to see the clients cookie value while the PHP is happening on the server side?
The reason is that each request to server also bring cookies in headers like i have inspected in chorome network tab, my php website and got this:
Cookies are store on client side but are accessible on server side through request header. As @Quentin stated in his answer "Every time the browser makes an HTTP request to one of those URLs, the cookie is included in the Request headers."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With