PHP / PHP Sessions and Cookies

Using Cookies for User Management

In this tutorial, you will learn how to use cookies for user management. We will cover how to set, retrieve, and delete cookies using PHP.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores session management and handling cookies in PHP.

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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

EXIF Data Viewer/Remover

View and remove metadata from image files.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help