Cookies is small text files saved locally on the user's computer by the website, when the website later on wants the information it just reads the cookie on the user's computer. An example on what you can use cookies for is to see if the user has visited the site before, if it has then a cookie you saved the last time lies on the computer so therefor you can only check if it does.
Creating a Cookie
When creating a cookie you have to do it before sending anything to the page, so you can't have a html tag before it. To create a cookie you do like this:
Here's an example on how to create a cookie:
The above example will create a cookie called "Cookie_Name" with the value "Test_Value" which will expire after 3 days.
Reading Cookies
To read a cookie you use:
and replace <Name of cookie> with the name of the cookie you want to read.
So if we want to read the cookie we created above we should do like this:
Here comes a simple example on reading a cookie:
So first of all we check if the cookie exists, if it do we reads it. Then recreate the cookie with an expire time of 3 days, this is so each time the user visit the site we will update the expire date, then we set the value to be a message telling what the value is, and if the cookie didn't existed we stored "Cookie not set" in the variable called Value. At the the end we just echo the result.
That was everything about how you're using cookies with PHP. I hope you found this tutorial useful.
Creating a Cookie
When creating a cookie you have to do it before sending anything to the page, so you can't have a html tag before it. To create a cookie you do like this:
PHP:
setcookie(name, value, expire, path, domain);
- Name - The name of the cookie, you use this to receive the cookie later.
- Value - The value that you'll store in the cookie.
- Expire - When the cookie will expire.
- Path - The path on the server where the cookie is available on, leaving this empty will allow whole domain to access it.
- Domain - The domain which can access the cookie, leaving this empty will allow all your domains to access it.
Here's an example on how to create a cookie:
PHP:
$expire=time()+60*60*24*3;
setcookie("Cookie_Name", "Cookie_Value", $expire);
Reading Cookies
To read a cookie you use:
PHP:
$_COOKIE["<Name of cookie>"];
So if we want to read the cookie we created above we should do like this:
PHP:
$_COOKIE["Cookie_Name"];
Here comes a simple example on reading a cookie:
PHP:
if (isset($_COOKIE["Cookie_Name"]))
{
$Value = $_COOKIE["Cookie_Name"];
$expire=time()+60*60*24*3;
setcookie("Cookie_Name", $Value, $expire);
$Value = "The Value of Cookie_Name is " . $Value;
}
else
{
$Value = "Cookie not set";
}
echo $Value;
That was everything about how you're using cookies with PHP. I hope you found this tutorial useful.