Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.