Source Code for /public/appendix-samples/remember-my-name.php

<?php
// Check if the user is submitting a name:
if( isset( $_POST['name'] ) ) {
  // If the user has submitted a name, store it in a cookie for 1 day:
  setcookie( 'name', $_POST['name'], time() + 60 * 60 * 24 * 1 );

  // Then reload the page and do nothing else
  header( 'Location: ' . $_SERVER['REQUEST_URI'] );
  die();
}

// Attempt to retrieve the user's name from their cookie -
// First - check if we have a name for them:
$has_name = isset( $_COOKIE['name'] );
// Second - set a $name variable either to their name (if we have it) or "Stranger" if we don't:
$name = $has_name ? $_COOKIE['name'] : 'Stranger';

// Remember that the user's name is user input and therefore untrustworthy -
// We'll need to use htmlspecialchars() to escape it and prevent XSS attacks!
?>
<h1>Hello, <?php echo htmlspecialchars( $name ); ?>!</h1>

<p>
  Welcome to my website.
  <a href="/demo-harness.php?file=public/appendix-samples/remember-my-name-here-too.php">I made a second page</a>
  which will also address you by name; take a look!
</p>

<h2>What's your name?</h2>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" autofocus
    <?php if( $has_name ) { echo 'value="' . htmlspecialchars( $name ) . '"'; } ?>
  >
  <button type="submit">👋 Hi!</button>
</form>