How come a server-side script like PHP is able to control client-side cookies?

486 views Asked by At

I'm a newbie and at the moment I'm learning PHP by designing a small and basic web page. I want to add a cookie handling script to my code. First I was planning to do it by Javascript. But when I browsed cookie managing functions of PHP and saw how detailed they are, I got very surprised.

But I don't understand the mechanism behind that. PHP is said to be a server-side script. How can it control cookies in my computer? How does it do that?

3

There are 3 answers

0
William The Dev On

When a user clicks a link, request headers are sent to the relevant server holing the website. The web server then responds using Reply Headers. The reply headers then have a space at the wnd that signal to the browser that the HTML is incoming.

The reply headers contain stuff like cookies, the encoding that incoming data will be in e.t.c. So the web server doesn't control the cookies per se but it instructs the browser on what to do and what to store i.e. cookies

0
CodeZombie On

Cookies are set by either setting HTTP Headers (server-side) or JavaScript (client side).

What PHP does when you call the setcookie() function is generate a HTTP response header like this:

Set-Cookie: name=value

For detailed information check this Wikipedia article: http://en.wikipedia.org/wiki/HTTP_cookie

0
gavstar On

The first time a browser visits a site, the php code can send back a cookie instruction at the front of the page content. When it gets back to the browser the browser sets a cookie record. This record can have a set lifetime. If the cookie is still set the next time the browser visits the server it sends that cookie along with the request. The php code can check it is set and decide what to do. For example, if the cookie is not set the server could send the login page instead of a content page that would be sent back if the cookie is set in the request. So yes, php does send cookie set orders to the browser.