PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

Sending and Receiving Cookies - Example

This section provides a tutorial example on how to set and send a cookie with the setcookie() function, and how to receive a cookie with the $_COOKIE array.

To help us understand how to send and receive cookies, I wrote the following PHP tutorial example script page, CookieTest.php:

<?php #CookieTest.php
# Copyright (c) 2005 by Dr. Herong Yang, http://www.herongyang.com/
#
   $numCookies = count( array_keys($_COOKIE) );
   $numCookies++;
   $cookieName = "Cookie_$numCookies";
   $cookieValue = "My cookie value";
   setcookie($cookieName, $cookieValue);

   print("<pre>\n");
   print("Cookies added by the server:\n");
   print("   $cookieName: $cookieValue\n");

   print("\nCookies received by the server:\n");
   foreach ($_COOKIE as $k => $v) {
      print "   $k = $v\n";
   }
   
   print "</pre>\n";
?>

When I ran run this script with a browser, I got:

Cookies added by the server:
   Cookie_1: My cookie value

Cookies received by the server:

When I click the refresh button of the browser, the page changed with:

Cookies added by the server:
   Cookie_2: My cookie value

Cookies received by the server:
   Cookie_1 = My cookie value

What happened here was that when I opened the page the first time, the server received no cookie from the browser's HTTP request. So my page added the first cookie named as "Cookie_1" to the HTTP response.

When I clicked the refresh button, the browser sent my first cookie back to the server in the HTTP request. Then my page added the second cookie named as "Cookie_2" in the response.

If I keep clicking the refresh button, more and more cookies would be added to the request and response. But there is a limit. The browser will only take up to 20 cookies from one Web server.

Last update: 2005.

Sections in This Chapter

What Is a Cookie?

Sending and Receiving Cookies

Sending and Receiving Cookies - Example

ob_start() - Output Buffering Function

Persistent Cookies Saved on Hard Disk

Other Cookie Properties - Domain and Path

Dr. Herong Yang, updated in 2009
Sending and Receiving Cookies - Example