PHP Cookies

setting Cookies

Because PHP executes code in sequence along with HTML, cookies must be set before the HTML header is sent. This is why the cookie must be set before the document type definition.

<?php
   session_start(); 
  $rating1=$rating;
  session_destroy();
  $today=time();
  $atoday=getdate($today);  //Get the date into an array
  $atoday->mon++;  //set the month to next month
  $month=$atoday->mon;
  $year=$atoday->year;
  if ($month > 12)
  {
    $month=1;
    $year++;
  }
  $cexpire=mktime(0,0,0,$month,1,$year);
  $linkid=$QUERY_STRING;  //get the link id number as an integer.
  global $slinkid, $cname;
  $slinkid=strval($linkid);  //convert to a string
  $cname="test";
  setcookie($cname,$slinkid,$cexpire);
?> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
   <meta name="GENERATOR" content="Arachnophilia 3.9">
   <meta name="description" content="Computer Technical Tutorials Rate Page">
   <title>Computer Technical Tutorials Rate Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>

In this example, the cookie is set to expire in one month. The name of the cookie is "test", and the cookie value is set to a link ID which is passed using a query string.

Getting Cookies

Appropriate cookies for the web site domain are automatically received by PHP and are placed into PHP variables automatically. The isset() function is used to test for their presence.

<?php
  global $rated;
  $rated=0;
  if (isset($rate))
  {
    echo "Cookie is set<br>";
    while (list ($name, $value) = each ($rate)) 
    {
      echo "$name = $value<br>\n";
    }
  }
?>

The each() function is used to get values from an array. The list() function is used to assign a list of variables into an array all at one time. Therefore the line "while (list ($name, $value) = each ($rate))" will increment through the $rate array getting the name of variables in the array with the value.

PHP Manual Contents Page