Setting Cookies in PHP

Learn, how to set cookies in PHP and learn the basics of cookies?
Submitted by Abhishek Pathak, on October 26, 2017 [Last updated : March 14, 2023]

Web programming is the heart of modern websites. It’s why the first version of PHP was written and what continues to make it so popular today. With PHP, it’s easy to write dynamic web programs that do almost anything. As a back-end developer it is important for you to focus on key web-specific concepts and organizational topics that will make your web programming stronger, and cookies is one of them.

What are cookies?

A cookie is a small text string that the server instructs the browser to send along with requests the browser makes. HTTP requests aren’t state full that is they don't contain information about the state. Also, each new request isn’t related to a previous one. A cookie, however, can link different requests by the same user. This makes it easier to build features such as shopping carts or to keep track of a user’s search history.

How to set cookies?

In order to work with cookies, we need to set the cookies first. We need to set a cookie so that a website can recognize subsequent requests from the same web browser and perform in a coherent manner, making pages linked to each other. In order to set cookie, we have to call setcookie() with a cookie name and provide it with a value, like

PHP code to set cookies

setcookie('flavor','chocolate chip');

If you are familiar with Advanced JAVA, you'll recognize the similar syntax in PHP. This cookie sets the cookie name flavor and a value associated with this cookie, chocolate chip. After setting the cookie, we can use it further in our programs. The setCookie() method has a third argument which is the expiration time. It is the time after which the cookie expires and will be not able to use in the program further.

The third argument to setcookie() is an expiration time, expressed as an epoch timestamp. For example, this cookie expires at noon GMT on December 3, 2014


setcookie('flavor','chocolate chip',1417608000);

If the third argument to setcookie() is missing (or empty), the cookie expires when the browser is closed, which is sometimes required in case of timer based applications. Therefore, it is the responsibility of the programmer to set correct cookie values and decide their expiration. The browser allows only limited number of cookies from a domain, so they should be used optimally for a good user experience.

This is how we set cookies in PHP? If you like the article, please share your thoughts in the comments below.

More PHP Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.