Using Cookies for User Management

Tutorial 2 of 5

1. Introduction

Goal of the Tutorial

This tutorial aims to provide a comprehensive guide on how to use cookies for user management using PHP.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand what cookies are and how they work.
- Set, retrieve, and delete cookies using PHP.
- Use cookies for managing user sessions and preferences.

Prerequisites

You should have a basic understanding of PHP and HTML.

2. Step-by-Step Guide

A cookie is a small piece of data stored on the user's computer by the web browser while browsing a website. Cookies were designed to be a reliable mechanism for websites to remember stateful information or to record the user's browsing activity.

To manage cookies, PHP provides three functions:
1. setcookie(): To set a new cookie.
2. $_COOKIE: A superglobal array holding all cookies.
3. setcookie(): To delete a cookie.

Setting Cookies with PHP

A cookie is set using the setcookie() function. This function must appear BEFORE the <html> tag.

<?php
setcookie(name, value, expire, path, domain, secure, httponly);
?>
  • name: Name of the cookie.
  • value: Content of the cookie.
  • expire: Expiry date and time of the cookie.
  • path, domain, secure, httponly are optional parameters.

Retrieving Cookies with PHP

Cookies are retrieved using PHP's $_COOKIE variable, an associative array of variables passed to the current script via HTTP Cookies.

<?php
echo $_COOKIE["user"];
?>

Deleting Cookies with PHP

A cookie is deleted by setting the expiration date to an already passed time.

<?php
setcookie("user", "", time() - 3600);
?>

3. Code Examples

Example 1: Setting a Cookie

<?php
setcookie("username", "John Doe", time() + (86400 * 30)); // 86400 = 1 day
?>

This sets a cookie named "username" with the value "John Doe". The cookie will expire after 30 days.

Example 2: Accessing a Cookie

<?php
if(!isset($_COOKIE["username"])) {
  echo "Cookie named 'username' is not set!";
} else {
  echo "Cookie 'username' is set!<br>";
  echo "Value is: " . $_COOKIE["username"];
}
?>

This script checks if a cookie named "username" has been set. If yes, it retrieves and prints the value.

Example 3: Deleting a Cookie

<?php
setcookie("username", "", time() - 3600);
?>

This sets the "username" cookie's expiration date to one hour in the past, effectively deleting it.

4. Summary

We've covered how to set, retrieve, and delete cookies using PHP. We also learnt how cookies can be used for managing user sessions and preferences. Now you can apply these concepts to manage user data in your PHP applications.

5. Practice Exercises

  1. Set a cookie storing the user's preferred language.
  2. Retrieve the language cookie and display a greeting in that language.
  3. Add a function that deletes all cookies.

Remember to test your scripts after each change. Happy coding!

For further reading, check out the PHP Cookies Documentation.