How to Set, Get and Delete Cookies in PHP?

This tutorial teaches you how you can set cookies, retrieve them and delete them using PHP. Cookies allow the webmaster to store information about the site visitor on their computer to be accessed again the next time they visit. One common use of cookies is to store your username and password on your computer so you don’t need to login again each time you visit a website. Cookies can also store other things such as your name, last visit, shopping cart contents, etc.

The main difference between a cookie and a session is that a cookie is stored on your computer, and a session is not. Although cookies have been around for many years and most people do have them enabled, there are some who do not. Cookies can also be removed by the user at any time, so don’t use them to store anything too important.

How to Set or create a Cookie

The setcookie() function is used for setting Cookie

Above we set the user name equal to ‘Arjun’, actually username will come from the database in real time for the sake of this tutorial i am using. and the cookie will expire in 1Hour.

PHP cookies can be set with more specific directives, including path, domain, secure, and httponly.

This cookie is the same as above,but It is for use only on an SSL connection and it may not be used by JavaScript.

How to Get or Retrieve a Cookie

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the above code, we retrieve the value of the user_name if cookie is set, and display it to the page

How to Delete a Cookie

To delete Cookie , just set the expiration date in past, bellow example expiration date set to 1Hour ago

REMEMBER:Cookies need to be set in the header. This means they must be sent before any HTML is set to the page, or they will not work.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
DMCA.com Protection Status
0
Would love your thoughts, please comment.x
()
x