0% found this document useful (0 votes)
10 views

Cookies_PHP_Example

COOKIES
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Cookies_PHP_Example

COOKIES
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Introduction to Cookies and PHP Example

What are Cookies?

Cookies are small pieces of information that websites save on your computer or phone. They help

websites remember things about you to make your experience better.

Simple Example:

When you visit an online store and add items to your cart, cookies remember what's in the cart,

even if you leave the website and come back later.

Why are Cookies Useful?

1. Remembering You: They keep you logged in so you don't need to log in every time.

2. Saving Preferences: If you choose dark mode or a specific language on a website, cookies

remember it.

3. Tracking Visits: Websites can see how often you visit and what you look at, which helps improve

their services.

Real-Life Example:

When you log into a streaming service like Netflix, cookies remember who you are, so it shows your

profile and favorite shows.

Below is an example program written in PHP to demonstrate the use of cookies.

<?php

// Set a cookie

if (!isset($_COOKIE['username'])) {

setcookie('username', 'JohnDoe', time() + 3600, "/"); // Expires in 1 hour

echo "Cookie 'username' is set!<br>";

} else {

echo "Welcome back, " . $_COOKIE['username'] . "!<br>";

}
// Option to delete the cookie

if (isset($_GET['delete'])) {

setcookie('username', '', time() - 3600, "/"); // Set expiration time in the past

echo "Cookie 'username' has been deleted.";

?>

<!DOCTYPE html>

<html>

<body>

<h1>PHP Cookie Example</h1>

<a href="?delete=true">Delete Cookie</a>

</body>

</html>

You might also like