Source Code for /public/appendix-samples/welcome-back-counter.php

<?php

// Set the visitor counter coookie to a specified value.
// The cookie lifespan is 7 days.
function set_or_update_visit_counter_cookie( $value ) {
  // Set a cookie for visited=?, where ? is the $value:
  setcookie( 'visited', $value, time() + 60 * 60 * 24 * 7 );
}

// See if a cookie is set:
if( isset( $_COOKIE['visited'] ) ) {
  // Get the value of the cookie and force it to be an integer
  $number_of_visits = intval( $_COOKIE['visited'] );

  // The cookie is set, so we welcome the user back.
  echo "👋 Welcome back! You've visited this page ";
  echo $number_of_visits;
  echo " time(s) before!";

  // Increase the visit count by 1:
  $number_of_visits++;

  // Re-set the cookie using our function:
  set_or_update_visit_counter_cookie( $number_of_visits );
} else {
  // Cookie is not set: welcome them!
  echo "🎉 Welcome! This is your first visit.";

  // Set the cookie using our function:
  set_or_update_visit_counter_cookie( 1 );
}