PHP Cookie Expiration 🎯

beginner
18 min

PHP Cookie Expiration 🎯

Welcome to our comprehensive guide on PHP Cookie Expiration! This tutorial is designed to help both beginners and intermediates understand and implement cookie expiration in PHP projects. Let's dive in!

What are Cookies? πŸ“

Cookies are small pieces of data stored on a user's computer by the web browser while browsing a website. They are used to store information about user preferences and session data. In this tutorial, we'll focus on how to control cookie expiration in PHP.

Setting a Cookie in PHP πŸ’‘

To set a cookie in PHP, we use the setcookie() function. Let's create a simple example:

php
<?php // Set a cookie named "user" with a value "John" and expire after 1 hour setcookie("user", "John", time() + 3600); ?>

πŸ“ Note: The third argument in setcookie() is the expiration time. It's set in seconds since the Unix timestamp.

Expiring Cookies in PHP πŸ’‘

By default, cookies set with setcookie() expire when the browser is closed. To set a specific expiration time, we can pass the expiration time as the third argument in setcookie().

php
<?php // Set a cookie named "user" with a value "John" and expire after 7 days setcookie("user", "John", time() + 7 * 24 * 60 * 60); ?>

πŸ“ Note: In the example above, we've calculated the expiration time by multiplying the number of seconds in a day (60 * 60) by the number of days (7), and then adding it to the current Unix timestamp.

Deleting Cookies in PHP πŸ’‘

To delete a cookie, we can set its expiration time to the past:

php
<?php // Delete the cookie named "user" setcookie("user", "", time() - 3600); ?>

πŸ“ Note: In the example above, we've set the expiration time to a time in the past (current time minus 1 hour).

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the third argument in PHP's `setcookie()` function represent?


That's all for this lesson on PHP Cookie Expiration! With these concepts in mind, you're now equipped to manage cookies in your PHP projects with control over their expiration times.

Stay tuned for more in-depth PHP tutorials here at CodeYourCraft! πŸ’‘πŸ“πŸ’ͺ