0
0
PHPprogramming~5 mins

Setting and reading cookies in PHP

Choose your learning style9 modes available
Introduction

Cookies help websites remember you by saving small pieces of information on your computer. This way, the website can greet you or keep you logged in next time.

Remembering a user's name after they visit your site.
Keeping a user logged in without asking for a password every time.
Saving user preferences like language or theme.
Tracking items in a shopping cart before checkout.
Syntax
PHP
<?php
// To set a cookie
setcookie('name', 'value', expire, path, domain, secure, httponly);

// To read a cookie
$_COOKIE['name'];
?>

setcookie must be called before any HTML output.

Only the name and value are required; others are optional.

Examples
This sets a cookie named 'user' with the value 'Alice' that lasts until the browser closes.
PHP
<?php
setcookie('user', 'Alice');
?>
This sets a cookie named 'user' that expires in 1 hour (3600 seconds).
PHP
<?php
setcookie('user', 'Alice', time() + 3600);
?>
This reads the 'user' cookie and greets the user by name if it exists.
PHP
<?php
if (isset($_COOKIE['user'])) {
    echo 'Hello, ' . $_COOKIE['user'];
} else {
    echo 'Hello, guest!';
}
?>
Sample Program

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

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

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

Cookies are sent with the HTTP headers, so setcookie() must be called before any output.

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

Use isset() to check if a cookie exists before reading it to avoid errors.

Summary

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

Use setcookie() to create cookies and $_COOKIE to read them.

Always check if a cookie exists before using its value.