CSC220 Cookie Example

From dftwiki3
Revision as of 08:57, 15 November 2010 by Thiebaut (talk | contribs) (Created page with '--~~~~ ---- <code><pre> <?php // cookie.php // D. Thiebaut // a program installing a cookie on the user's computer // and reminding him/her of the number of visits he/s…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 13:57, 15 November 2010 (UTC)



<?php
  // cookie.php
  // D. Thiebaut
  // a program installing a cookie on the user's computer
  // and reminding him/her of the number of visits he/she
  // has made to the page.
  //

//--- if no cookies yet, create one with an expiration of 30 sec ---
if ( empty( $_COOKIE[ '220class' ] ) ) {
    setcookie( "220class", "1", time()+30 );
    $count = 1;
}
//--- else, increment the cookie counter, with an expiration of 30 sec ---
else {
    $count = intval( $_COOKIE[ '220class' ] );
    $count++;
    setcookie( "220class", "$count", time()+30 );
}

?>

<html>
<head>

</head>
<body>

<h1>cookie example</h1>

<?php printf( "(<a href=\"%s\">Source</a>)", str_ireplace( ".php", ".txt", $_SERVER[ 'PHP_SELF' ] )); ?>

<p>Hello! This is your 

<?
// $count set to 1 or read from $_COOKIE[]
switch ( $count ) {
    case 1: print "first visit"; break;
    case 2: print "second visit"; break;
    case 3: print "third visit"; break;
    case 21: print "21st visit"; break;
    case 22: print "22nd visit"; break;
    case 23: print "23rd visit"; break;
    default: print "${count}th visit";
}


print '<P>$_COOKIE as found by the browser: <pre>';
print_r( $_COOKIE );
print "
\n

\n";

?>

</body> </html>


</pre></code>