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 webrewrite.com cannot be accessed by example.com .
The size of Cookie cannot be more than 4096 Bytes which is 4 KB.
How to Set a Cookie in PHP
In PHP setcookie() method is used to set a cookie.
setcookie(name, value, expire, path, domain, secure);
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.
$cookiename = "firstcookie";
/* Set time interval of two hours */
$time = time() + (60 * 60 * 2);
/* Cookie name first */
setcookie("product", $cookiename, $time);
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 Set Cookies for Multiple Subdomains
Take an example of webrewrite.com. Suppose this website has multiple subdomains such as tech.webrewrite.com , tuts.webrewrite.com 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.
/* .webrewite.com indicates my cookie is valid across all the subdomain of webrewrite.com .*/
setcookie("first", $cookiename, $time , "/", ".webrewrite.com");
/ – If a path is set / in that case a cookie will be available to scripts within the entire domain.
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.
// cookiename is the name of cookie you set
$cookievalue = $_COOKIE["cookiename"];
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.