PHP Cookie Path/Domain 🎯

beginner
10 min

PHP Cookie Path/Domain 🎯

Welcome to our deep dive into PHP Cookies Path and Domain! This tutorial is designed for both beginners and intermediate learners, so let's get started!

What are Cookies? πŸ“

Cookies are small pieces of data stored on a user's computer by a web browser while browsing a website. They are used to remember user preferences, session information, and more.

Cookies Path and Domain πŸ’‘

Cookies can be limited to a specific path and domain for security and privacy reasons. In PHP, you can set cookie path and domain using the setcookie() function.

Setting Cookie Path πŸ“

The path attribute specifies the path within the domain where the cookie can be accessed. If no path is specified, the cookie can only be accessed by the current path.

Here's a simple example of setting a cookie with a specified path:

php
// Set a cookie with path "/admin" setcookie("admin_cookie", "value", time() + (86400 * 30), "/admin");

In this example, the admin_cookie will be accessible only within the /admin path.

Setting Cookie Domain πŸ“

The domain attribute specifies the domain where the cookie can be accessed. If no domain is specified, the cookie can only be accessed by the domain that set it.

Here's an example of setting a cookie with a specified domain:

php
// Set a cookie with domain "example.com" setcookie("example_cookie", "value", time() + (86400 * 30), "/", "example.com");

In this example, the example_cookie will be accessible on the entire example.com domain.

Path and Domain Combination πŸ’‘

You can also combine path and domain while setting a cookie.

php
// Set a cookie with path "/admin" and domain "example.com" setcookie("admin_cookie", "value", time() + (86400 * 30), "/admin", "example.com");

In this example, the admin_cookie will be accessible only within the /admin path on the example.com domain.

Secure Cookies πŸ“

If the secure attribute is set, the cookie will only be transmitted over secure connections (HTTPS).

php
// Set a secure cookie setcookie("secure_cookie", "value", time() + (86400 * 30), "/", "example.com", true);

In this example, the secure_cookie will only be sent over secure connections (HTTPS).

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

What does the path attribute in PHP's `setcookie()` function do?

Quick Quiz
Question 1 of 1

What does the domain attribute in PHP's `setcookie()` function do?

We hope this tutorial has helped you understand PHP's Cookie Path/Domain concept! Happy coding! πŸ₯³