How to Set Cookies for Multiple Subdomains


How to set cookies for multiple subdomains. In this post, You’ll learn how to set and read a cookie across multiple subdomains.

HTTP is a stateless protocol it means requested resource is served without the server remembering the request later. So how website knows whether you are a unique user or you have visited previously. How they remember your previous browsing history, language preference etc.

The answer is they simply store information in a user browser through cookies. When you again visit the same website the cookie information is sent via HTTP Header to the server. Before going further let’s understand what is cookies.


Cookies are simple text files which store some information on a user computer . The information may be website language preference,visit count,name,category,browsing history etc. Cookies set by one website cannot be accessed by other websites. For security point of view, it is safe. This means cookies set by cannot be accessed by .

The size of Cookie cannot be more than 4096 Bytes which is 4 KB.

Cookies in PHP – Create, Read, and Delete Cookies

How to Set a Cookie in PHP

In PHP setcookie() method is used to set a cookie.

Subscribe Our Tutorials

Get Latest Updates on Facebook


Name – Name of a Cookie

Value – Value which you want to store in a cookie

expire – Set Cookies expiration time. If it is not set in that case a Cookie will expire when the connection to the server is closed.

path – specifies server path for the cookies.

domain – specifies a domain for which cookie is set.

secure – If this parameter is true in that it set a cookie when secure connection is detected.

This snippet set a cookie (with a cookie name product)  with an expiration time of 2 hours.

** Remember cookie only store string values. If you want to store an array in a cookie then you have to first convert an array into a string.

How to store and retrieve an array value in a cookie.

How to Set Cookies for Multiple Subdomains

Take an example of Suppose this website has multiple subdomains such as , etc. and I want to set a Cookie for all subdomains, In that case, I have to mention a domain name with a dot prefix.

/ – If a path is set / in that case a cookie will be available to scripts within the entire domain.

.htaccess Tutorial

Read a Cookie in PHP through $_COOKIE

Now our cookie is set into a user computer. How to read a cookie value in PHP.  We can do it through $_COOKIE.

Final Thought

1. There is a limit to how many cookie can set per domain.

2. Always set an expiration date for a cookie.

3. Try to avoid storing sensitive data in a Cookie.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.