All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP Cookies

PHP Cookies are used to store information on user device like computer, mobile phones etc. You can store create cookies, access cookies and delete cookies.


You can set as many Cookies as you want.You can also set cookies with the help of JavaScript.



Create Cookies

Cookies are created with help of setcookie() function.


Syntax Of creating a cookie


setcookie(name, value, expire, path, domain, security);

Code Explanation

  • name is the name of the cookie it works like variable to identify the cookie.

  • value is the value you want to store in the cookie.

  • expire is the time the cookie remain in the user device and when the time expire the cookie deleted automaticall from the user device.

  • path is the path of the directory for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

  • domain is the name of the website so that the cookie can be accesible only for that website no other website can access your cookie

  • security this can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.



Example of How to set Cookie

setcookie("Course", "B-Tech", time()+3600, "/","", 0);

Code Explanation

  • Course is the name of the cookie, B-Tech is the value stored in the cookie.
  • time() is the php built in function it gives the present time and time()+3600 means the cookie will expire after 1 hour.
  • / is used so that the cookie is accessible to all directory of that domain



Example of Access the Cookie

You can access the cookie with $_COOKIE or $HTTP_COOKIE_VARS variables.


echo $_COOKIE["Course"];

/* Or you can use other method */

echo $HTTP_COOKIE_VARS["Course"];


Both the methods display the value stored in cookie variable In this B-Tech will displayed.




Example of Deleting the Cookie

to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.


It is safest to set the cookie with a date that has already expired:


setcookie( "Course", "", time()- 60, "/","", 0);
❮ PrevNext ❯