Using Cookies in PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Using Cookies in PHP

Hi everyone, at the time this article was written, I was very hungry, and yeah … this is pretty much the place where the inspiration begins. So let’s cut to the serious things now and let me show you really quick how is using cookies in php.

What are cookies ?

Cookies are simply files stored in a special temporary location determined by your web browser (like Firefox) which allow public information to be stored for your benefit usually. The problem with cookies is that they are very misunderstood. People think that they are harming to your pc and they are built to steal information from you. This is not true, but since we are developers, we have a more opened mind and we see the real truth.

How to Set Cookies

Php allows us to set a cookie in the user’s browser with the setcookie() function. This function does exactly what it says. It defines a cookie to be sent along with the rest of the HTTP headers.

Like other headers, cookies must be sent before any output from your script. This requires that you place calls to this function prior to any output, including<html> and <head> tags as well as any whitespace.

Let’s see an example of how we set a cookie in php:

Pretty straight forward, huh ?

How to retrieve and use cookies ?

 Expiration date for cookies ?

You can set a cookie to expire at a given date.

In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days). So this cookie will be available in the user’s browser for an entire month, and you can manipulate it how you want, unless the user is clearing his browser’s cookies manually.

Summary

In the end, we learned that cookies are not bad (of course they are not, they are delicious :)), we should not be afraid of them as regular users and definitely use them as developers.

Request an article ←