PHP Cookies

PHP Cookies

Cookies are small text file stored on client computer, used to identify a user.

Cookies store a user information like username and password on client computer for further use.
User use same computer many time each time it will send a cookie too.
In PHP we can create a cookie and retrieve cookie values.


Create Cookies with PHP

  • The setcookie() function used to create a cookie.
  • A single domain has maximum 20 cookies.
  • A single cookie can not exceed 4 kilobytes in size.
  • PHP setcookie() function must be called before <html> tag.
  • The setcookie() function has up to six arguments.

setcookie() function syntax:

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

Name : This is name of the cookie and it is used to retrieve cookie.
Value : information or value to be stored in cookie.
Expire : used to set time of expiry of cookie. If not set expiry the cookie automatically expire when browser closed.
Path : “/” means the cookie available in entire website or all directories. or we can specify the directories for valid cookie.
Domain : used to specify the domain name.
Security : used to security purpose. set 1 or 0, 1 for secure transmission using HTTPS and 0 for sent by simple HTTP.

Example of create cookies

setcookie(“example”, “meera”, time() + 3600, “/”, “”, 0);

Here, we create cookie named “example” with value “meera”. The cookie will expire after 1 hour. The “/” means cookie available in all directories.

PHP Example :

Create php form with named “example.php” for create cookie name and id.


Retrieve cookies in PHP

The cookies retrieve using the $_COOKIE[] global variable.
The isset() function used to check if a cookie is set or not.

Example  if retrieve cookies in PHP.

Create php form “cexample.php” with below code for retrieve cookie name and id.

In above example out put is :

The name = meera
The id = 25


Delete / Destroy cookies in PHP

For delete a cookie, use setcookie() function with date that already expired.

Create php form “dexample.php” for delete cookie name and id.

PHP cookies create , retrieve and delete example.

PHP  cookies example

PHP cookies example

Leave a Reply

Your email address will not be published. Required fields are marked *

9 + 9 =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">