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

PHP Browser Persistent Data with PHP Data Persistence on the Web Cookies

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 Points

Can I just ask about parameters of setcookie

I was able to pass the code challenge.

However I was left a little confused. I need to know if the order of parameters makes a technical differents to a cookie in practice.

The code challenge asks us for the parameters and to pass it I had to give the path as the 4th parameter after the timestamp. I guess it's this order because that's the order the challenge asks for it but does it make a real difference?

<?php
//add cookie below this line
setcookie("cookiename", "value",  "timestamp", "path");

or

<?php
//add cookie below this line
setcookie("cookiename", "value",  "path", "timestamp");

1 Answer

It actually does matter. If you swap the path and the expiration you're going to get some amount of weirdness. Your cookie will be set to expire on '/' and be for directory '2018-01-20 10:14' for example.

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 91,253 Points

So there is an order to it that I'm going to have to learn. Thanks. :-)

Yes sir. setcookie('name', 'value you want later', 'expiration date', 'path such as /dashboard/', 'domain such as www.teamtreehouse.com', 'TRUE/FALSE for whether it only works over https', 'TRUE/FALSE for HTTP protocol only so will not work for scripting languages such as JavaScript').

So to set a cookie for the Treehouse forums it would go something like:

<?php
setcookie('cookie', 'will need this later', '2018-01-20 10:14', '/community/', 'www.teamtreehouse.com', TRUE, TRUE)
?>

EDIT: For the expiration date the easiest way to programmatically set the date is to use the time() or mktime() function. time()+60*60*24*30 is good for 30 days (seconds, minutes, hours, days respectively).