Advertisement

Cookies in PHP

COOKIES IN PHP

Cookies are used to store user data related to a site on the user’s computer. This data is used to identify the user. Cookies are files on the user’s computer which are saved on the server.

The logic behind the cookies is that sometimes we need to store data for small time and if we save that data in server or database, then a problem arises that there are so many users and due to this a huge amount of data needed to store on the server, which may create some memory issue so to avoid that danger the server stores that data on user’s PC and retrieve it on demand.

Example:

Like while online shopping we add items in the cart, and sometimes we discard that cart without shopping. So if we save all the cart data in our database or server files, this will take server’s time and memory, can also reduce the response time of the server. So we save that data in cookies and if user discards his cart, then we simply unset the cookie.

Another example of cookies is related to authentication of users as while logging in to Facebook or some other site we see an option on remember me with a check box and if we check this, then the browser remember us up to some limit of time that was set by the developer.

How to use cookies in PHP?

Cookies implementation in PHP:

One thing to remember as we see in syntax the setcookie( ) function take six parameters, but the only name parameter is required, all others are optional but the cookie value and expire time is an important part of cookies and if they are not set by default they are 0.

Example:

1

2

3

<?php

setcookie("user","Usman",time()+86400);

?>

In the above example, the cookie name is user, and its value id Usman and the expire time for that cookie was the time when we create that cookie plus 86400 which is equal to 1 day like cookies take time in second so (60seconds60minutes24 = 86400)=1 day.

Get value from cookie in PHP:

To get value from cookie simple, we have to get it from cookies variable same as a post, get and session when we save some value in the cookie variable it makes an associative array.

Syntax:

$_COOKIE [‘cookie named’];

Example:

As we create a cookie above with the name user so to get the value of the user simple call this index using user like:

$_COOKIE [“user”];

Note:Something to remember while working with Cookies: The cookies must be created before <html> tag and second while getting cookie value the keyword $_COOKIE must be in capital letters.

Example code:

The following code is for to remember a user for a long time on the site.