1 min read

PHP Cookies and Sessions

Cookies and Sessions are used to manage user state and data across different pages of a website.


1. Cookies

A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too.

Use setcookie() before any HTML output.

// Name, Value, Expiration (86400 = 1 day), Path
setcookie("user", "John Doe", time() + (86400 * 30), "/");

Use the $_COOKIE superglobal.

if(!isset($_COOKIE["user"])) {
  echo "Cookie named 'user' is not set!";
} else {
  echo "Value is: " . $_COOKIE["user"];
}

2. Sessions

A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer, but on the server.

Starting a Session

Use session_start() at the very beginning of your script.

<?php
session_start();
?>

Storing and Retrieving Session Variables

Use the $_SESSION superglobal.

// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";

// Get session variables
echo "Favorite color is " . $_SESSION["favcolor"];

Destroying a Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy().

session_unset();
session_destroy();

programming/php/php