PHP Cookies Introduction 🎯

beginner
17 min

PHP Cookies Introduction 🎯

Welcome to our PHP Cookies tutorial! In this lesson, we'll dive into the world of HTTP cookies, a powerful tool in web development that helps us store small pieces of data on a client's browser. Let's get started!

What are Cookies? πŸ“

Cookies are small text files saved by a web browser on your computer when you visit a website. They are used to store information about your visit, such as your preferred language, login information, and other preferences.

Why Use Cookies in PHP? πŸ’‘

Cookies play a crucial role in web development, helping us to:

  1. Store user preferences, such as language or theme
  2. Authenticate users, allowing them to stay logged in without repeatedly entering their credentials
  3. Track user behavior for analytics and marketing purposes

How Do Cookies Work in PHP? 🎯

When a user visits a PHP-powered website, the server can send cookies to the browser. The browser saves the cookies and sends them back to the server whenever a request is made to the same domain.

Let's write our first PHP cookie!

php
// Set a cookie named "myCookie" with value "Hello, World!" and expiry in 1 hour setcookie("myCookie", "Hello, World!", time() + 3600);

In this example, we're creating a cookie named myCookie with the value "Hello, World!" and setting its expiry time to 1 hour after it's created.

Retrieving Cookies in PHP πŸ“

To retrieve a cookie, we can use the $_COOKIE superglobal array.

php
// Check if the "myCookie" cookie exists if (isset($_COOKIE["myCookie"])) { echo $_COOKIE["myCookie"]; // Outputs: Hello, World! }

In this example, we're checking if the myCookie cookie exists and, if so, we're displaying its value.

Advanced PHP Cookies 🎯

Cookies can be set with various attributes such as expiry date, path, domain, and secure flag. Let's create an example using these attributes:

php
// Set a secure, encrypted, and persistent cookie named "mySecureCookie" // The cookie expires in 30 days and is available only on the example.com domain setcookie("mySecureCookie", "Secret Data", time() + (60 * 60 * 24 * 30), "/", "example.com", true, true);

In this example, we're creating a secure, encrypted, and persistent cookie named mySecureCookie that expires in 30 days and is available only on the example.com domain.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Which attribute makes a cookie secure?

Stay tuned for more PHP tutorials on CodeYourCraft! Happy learning! πŸš€