How to set cookies for multiple subdomains. In this tutorial, You are going to learn how to set and read a cookie from multiple subdomains.
HTTP is a stateless protocol. Stateless means client request a resource a server respond to that request 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 visit next time on a same website the cookie information is sent via HTTP Header to the server. Before going further let’s understand what is cookies.
What is Cookies in PHP?
Cookies are simple text files which store some information on a user computer. The information may be website language preference, visit count, last visit information etc. Cookies set on one domain or website cannot be accessed by other domains. For security point of view, it is safe. So cookie 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.
//Syntax 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 case a cookie is set when a 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 a 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
Let’s take an example of webrewrite.com. Suppose this website has multiple subdomains such as tech.webrewrite.com, tuts.webrewrite.com etc. We 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.
How to Read a Cookie in PHP
Now we have set a cookie successfully. How to read a cookie 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 cookies can set per domain.
2. Always set an expiration date for a cookie.
3. Try to avoid storing sensitive data in a Cookie.