Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion HTTP: Do You GET It?

Who sets the cookie?

Lets say:

  1. I open a website "Google.com". My browser will send a HTTP request to the server(google)
  2. Google will reply with a HTML page in its HTTP response.

From what I understand , a cookie is used by the server to maintain the state of the user. So, how and when is the cookie set? Im confused.

1 Answer

The cookie is set within the code based on certain criteria (signed up for a mailing list, first visit, login, etc). For example on a php site you could do:

$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);

And do this on page load so that any user would immediately have a cookie created. You can also use javascript to do the same thing. If a user visited a page, and got a pop-up for a mailing list, it would typically be set to create a cookie if the pop-up is closed so that they won't get it on the next visit.