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 Writing Cookies

Why is it better to set the file path to route rather than just leave it as the default path?

Hi all

I'm not too clear on why it is better to set the setcookie file path to the root of the site rather than just leave it as the default path that makes the cookie only available in the inc folder. What difference does it make to the functionality of the site and the persistence of the data as to what the file path is?

2 Answers

Hi Matt!

I found this:

How to set the path for a cookie in JavaScript

Sometimes you'll only want your cookie to work with certain parts of your website. Depending on how your website is set up, one way to do this is with the path attribute.

Here's how to make it so a cookie only works on the about page at /about:

document.cookie = 'dark_mode=true; path=/about';

Now your cookie will only work on /about and other nested subdirectories like /about/team, but not on /blog.

Then when you visit the about page and check your cookies, you'll see it:

[IMAGE)

See full article here:

https://www.freecodecamp.org/news/everything-you-need-to-know-about-cookies-for-web-development/

More info:

https://javascript.info/cookie

https://www.w3schools.com/js/js_cookies.asp

https://html.com/resources/cookies-ultimate-guide/

I hope this all helps.

Stay safe and happy coding!

Ok thanks Peter. So in this case, I guess it is correct that the cookie wouldn't actually work in story.php unless the path was set to the root?