In web applications, maintaining state and tracking user information across multiple pages can be a challenge. Sessions and cookies are two common techniques used to store data across different pages and visits. In this lesson, we'll explore how to work with PHP sessions and cookies to create persistent user experiences.

Cookies

Cookies are small pieces of data stored on the user's browser, which can be accessed and modified by the server. They are useful for storing non-sensitive data, such as user preferences or tracking information.

  1. Setting a cookie:
setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // Expires in 30 days
  1. Reading a cookie:
$username = $_COOKIE["username"];
  1. Deleting a cookie:
setcookie("username", "", time() - 3600, "/"); // Set the expiration time to the past

Sessions

Sessions provide a more secure way to store sensitive data on the server, and are commonly used for managing user authentication and authorization.

  1. Starting a session:
session_start();
  1. Storing data in the session:
$_SESSION["username"] = "JohnDoe";
  1. Accessing session data:
$username = $_SESSION["username"];
  1. Removing session data:
unset($_SESSION["username"]);
  1. Ending the session: