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.
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.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.