0
0
PHPprogramming~5 mins

How cookies work in PHP

Choose your learning style9 modes available
Introduction

Cookies help websites remember you. They store small bits of information on your computer so the site can recognize you later.

Remembering a user's login so they don't have to sign in every time.
Saving user preferences like language or theme on a website.
Tracking items in a shopping cart while browsing an online store.
Keeping a user logged in during a session.
Collecting simple data for website analytics.
Syntax
PHP
<?php
setcookie(name, value, expires, path, domain, secure, httponly);
?>

name is the cookie's name.

value is the data stored in the cookie.

expires is the time the cookie expires (as a Unix timestamp).

Only name and value are required; others are optional.

Examples
Sets a cookie named 'user' with value 'Alice' that lasts until the browser closes.
PHP
<?php
setcookie("user", "Alice");
?>
Sets a cookie named 'theme' with value 'dark' that expires in 1 hour.
PHP
<?php
setcookie("theme", "dark", time() + 3600);
?>
Sets a secure, HTTP-only cookie for the domain 'example.com' that expires in 1 day.
PHP
<?php
setcookie("session", "12345", time() + 86400, "/", "example.com", true, true);
?>
Sample Program

This program sets a cookie called 'visitor' with the value 'John' that lasts for one hour. Then it checks if the cookie exists and greets the visitor by name if it does. If not, it welcomes a new visitor.

PHP
<?php
// Set a cookie named 'visitor' with value 'John' that expires in 1 hour
setcookie("visitor", "John", time() + 3600);

// Check if the cookie is set and print a message
if (isset($_COOKIE["visitor"])) {
    echo "Welcome back, " . $_COOKIE["visitor"] . "!";
} else {
    echo "Hello, new visitor!";
}
?>
OutputSuccess
Important Notes

Cookies must be set before any HTML or output is sent to the browser.

Cookies are stored on the user's computer and can be deleted by the user anytime.

Cookies can only store strings, so complex data must be converted (e.g., using JSON).

Summary

Cookies store small data on the user's computer to remember information.

Use setcookie() in PHP to create cookies.

Cookies help improve user experience by saving preferences and login info.