Cookie setting or removal in PHP

Cookie setting or removal in PHP

In PHP, you can set or remove cookies using the setcookie() and setrawcookie() functions, respectively. Here’s an example of how to set a cookie in PHP:

// Set a cookie with the name "username" and value "john"
setcookie("username", "john", time() + 3600, "/");

This sets a cookie with the name “username”, a value of “john”, an expiration time of one hour from the current time, and a path of “/”.

To remove a cookie, you can use the same function, but with an expiration time in the past:

// Remove the "username" cookie
setcookie("username", "", time() - 3600, "/");

This sets the value of the “username” cookie to an empty string and an expiration time in the past, causing the browser to remove the cookie.

Note that cookies can only be accessed on subsequent requests, so you may need to refresh the page or navigate to a new page to see the effects of setting or removing a cookie. Additionally, cookies can only be accessed on the same domain that set them, so you can’t set a cookie on one domain and read it on another.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Secondary Market
Repeating yourself with the Repeater

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?