How To Use Cookies in Php Examples

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users −

  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • Browser stores this information on local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

In this tutorial you will find information about creating and managing cookies in php examples

Create Cookies In Php Examples

A cookie is created with the setcookie() function. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.


Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value − This sets the value of the named variable and is the content that you actually want to store.

Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.

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.

Following example will create two cookies name and age these cookies will be expired after one hour.

Note: The setcookie() function must appear BEFORE the <html> tag.

This will produce the following result –

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

This will produce the following result –

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past:

This will produce the following result –

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

This will produce the following result –

Trust this instructional exercise helped you a lot, keep reading our various posts for more coding Tricks and Tips. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub