Create Cookies using PHP functions

Create Cookies using PHP functions

Jul 16, 2018 | PHP

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required in this function. All other parameters are optional.

Setting a cookie with PHP could not be easier, since PHP provides a function for you to do precisely that. The following code sets a cookie called “userlogin” with a value of “anonymous”:

$date_of_expiry = time() + 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry );

We then retrieve the value of the cookie “user” (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

Example

 

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

<?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];
}
?>

</body>
</html>?

 

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example

<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?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];
}
?>

</body>
</html>?


How to Delete a Cookie

Cookies can also be deleted. This is useful for situations such as when a user logs out of your site. To delete a cookie, call the setcookie() function again with the same name, folder and domain that you used earlier to set the cookie. However, instead of an expiry date set in the future, this time give an expiry date some time in the past.

$date_of_expiry = time() - 60 ;
setcookie( "userlogin", "anonymous", $date_of_expiry, "/", "example.com" );?

The above code simply sets the expiry date 60 seconds in the past, effectively making the cookie no longer valid.

Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

0 Comments

Leave a Reply