A cookie is a small text file in which a website can store different information. Cookies are saved on the user's hard drive and not on the server.
Most cookies expire (delete themselves) after a predetermined time period, which can range from one minute to several years. But the user can also identify and delete any cookies on his/her computer.
Most browsers, such as Microsoft Internet Explorer, Mozilla Firefox and Google Chrome, can be configured to let the user choose whether or not he/she will accept a cookie. But then, why not just say no to all cookies? It is possible. But many websites would not work as intended without cookies, since cookies in many contexts are used to improve the usability and functionality of the website.
How is information stored in a cookie?
It's easy to set or modify a cookie in PHP with setcookie. In the first example, we will create a cookie and set the value.First, you need a name for the cookie. In this example we will use the name "HTMLTest". Next, you set the value of the cookie like this:
<?php // Setting the cookie setcookie("HTMLTest", "This is a test cookie"); ?>
<?php // Setting the cookie setcookie("Name", "C. Wing, time()+3600); setcookie("Interests", "plane spotting", time()+3600); ?>
In the example above, we stored information about a user's name and interests. This information can, for example, be useful to target the website specifically for the individual visitor.
How do you retrieve the value of a cookie?
To get the value of the cookie, $_COOKIE is used. For example, if we need the information from the example above, we do it like this:<?php // Retrieve values from the cookie $strName = $_COOKIE["Name"]; $strInterest = $_COOKIE["Interest"]; // Write to the client echo "<p>" . strName . "</p>" echo "<p>Your interest is . " strInterest . "</p>" ?>
Who can read the cookie?
By default, a cookie can be read at the same second-level domain (e.g. prog-teach.blogspot.com ) as it was created. But by using the parameters domain and path, you can put further restrictions on the cookie using the following syntax:setcookie(name, value, expiration time, path, domain);
<?php // Setting the cookie: name, value, expiration time, path, domain setcookie("Name", "C. Wing", time()+60*60*24*365, "/tutorials/php/", "www.prog-teach.blogspot.com"); ?>
Example of a cookie
We can try to save a sample cookie on your computer and then see how it looks.The following code sets the cookie:
<?php // Setting the cookie setcookie("HTMLTest", "This text is in a cookie!", time()+60*60*24, "/tutorials/php/", "www.html.net"); // Write the information to the client echo $_COOKIE ["HTMLTest"]; ?>








filenameand parses it line by line for <meta> tags in the file. The parsing stops at </head>.