How to make cookies on php

Create cookies using PHP with examples: Learn how to set, get and delete cookies using PHP with code examples.

Making Cookies with PHP

Cookies are small pieces of information that are stored on a user's computer. They are used to remember user preferences and settings, store login information, and other important data. PHP can be used to create and manage cookies, allowing developers to create dynamic and interactive webpages.

Cookies are created with the setcookie() function. This function takes several parameters, including the name, value, and expiration date of the cookie. Here is an example of creating a cookie with PHP:


setcookie("favorite_color", "blue", time() + (86400 * 30));

This code creates a cookie named favorite_color with a value of blue. The cookie will expire after 30 days. It is important to note that the setcookie() function must be called before any HTML is sent to the browser. Otherwise, the cookie will not be set correctly.

Once the cookie is created, it can be accessed with the $_COOKIE global array. Here is an example of retrieving a cookie:


$favorite_color = $_COOKIE["favorite_color"];
echo "Your favorite color is $favorite_color";

This code retrieves the value of the favorite_color cookie and prints it out. This is a simple example, but cookies can be used in more complex ways as well.

Cookies are an important tool for creating dynamic and interactive websites. With PHP, it is easy to create, manage, and retrieve cookies. With just a few lines of code, developers can create powerful web applications that remember user preferences and settings.

Answers (0)