What is a Cookie?

The cookies are often used to identify users. A cookie contains a small file that server embeds on the user’s computer when he/she access the website through browsers. By using php cookie code you create and retrieve its value.

Example:

[php]<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>[/php]

[php]<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named ‘" . $cookie_name . "’ is not set!";
} else {
echo "Cookie ‘" . $cookie_name . "’ is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>[/php]

Code example

First, we set the cookies by using variables. The variable $cookie_name has the value user and $cookie_value has the value John Doe.

Then on the next line, we are using the setcookie() function to set the cookie for the user.

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

In the setcookie() function the first variable is used for the user. The second is used for value and finally, the time period is described by using time() function. We have declared 30 days for the cookie to set on the user computer. The “/” is describing that we want to set the cookie for the entire website.

Note: The cookie function must start before the HTML code.

Once the cookie function is set, we will produce the outcome in the HTML format.

We are using if statement with isset function to set the cookie. The global variable $_COOKIE is used in the isset() function.
On the next line, we are using echo statement to check the browser whether the cookie is set or not. If it is not set then it will show is not set message. Else it will render the else statement and show the output.

The code generates the following result.

Cookie 'user' is set!
Value is: John Doe

Delete a Cookie

The cookie can be deleted by using the setcookie() function with the expiration date in the past.

Example:

[php]<?php
// set the expiration date to one hour ago
setcookie("user", "", time() – 3600);
?>[/php]

[php]<?php
echo "Cookie ‘user’ is deleted.";
?>[/php]

Code Explanation:

In the above code, the setcookie() function is set to the past timer which in this case is “-3600“. This will delete the cookie completely.

Check if Cookies are Enabled

You can run the function count to check the cookies are enable or disable.

Example:

[php]<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>[/php]

Code Explanation;

By using if statement we first count the cookie. If it shows value bigger than zero then it will state the cookies are enabled. Else the next echo statement will render saying the cookies are disabled.

Related Posts

Leave a Reply