welcome2.php

<?php
/* Cookie demo: this is page 2, illustrating how access to content can
   be limited to cookie holders.

   Script is in 3 sections:

   1. Preliminaries where the existence of cookie is determined.  This
   needs to be done early, before any output, so the cookie can be
   reset to extend the timer.

   2. Welcome section, where the visitor gets to see the site content
   based on the cookie being set.

   3. Regret section, in case user somehow reaches this page before
   cookie is set.  Visitor is told to go and register first.

 */

/* Section 1: preliminaries */

  $cookie_name = 'whatsyourname';   // name of cookie holding visitor name
  $timeout = 3600; // time for cookie to expire, in seconds: 1 hour

// The setcookie call needs to precede any output, so we check here and
  $cookie_set = isset($_COOKIE[$cookie_name]);
  if( $cookie_set ) {
    $visitor_name = $_COOKIE[$cookie_name];
// set the cookie again so that expiration timer is reset by visit activity
    setcookie($cookie_name,$visitor_name,time()+$timeout);
  }
?>

<!DOCTYPE html>
<html lang="en">
  <head>
<?php
  if( $cookie_set ) {
?>
    <title>Page Two</title>
<?php } else { ?>
    <title>Sorry</title>
<?php } ?>
    <meta charset="utf-8">
  </head>
  <body>
    <pre>
<?php
// Print the cookies and post data as debugging aid.
// Escape special characters: print_r(x,true) means return a string instead of printing
 print '$_COOKIE: ' . htmlspecialchars(print_r($_COOKIE,true));
 print '$_POST: ' . htmlspecialchars(print_r($_POST,true));
?>
    </pre>
    
<?php
/* Section 2: Welcome */

  if( $cookie_set ) {
?>
  <h1>Page Two</h1>
<p>You are registered,
<?php
  print htmlspecialchars($visitor_name) . '.';
?>
  Return to <a href="welcome.php">welcome page</a>.
  </p>
<?php } else {
/* Section 3: Not registered  */
?>
    <h1>Sorry!</h1>
  <p>You must register to see the site content.  <a href="welcome.php">Register here</a>.
  </p>
<?php } ?>
  </body>
</html>