Source Code for /public/07-storing-data/clap.php

<?php
// Define our file name in a constant so it's easy to use in
// multiple places:
define('CLAP_FILE_NAME', '../../private/clap-count.txt');

// A convenience function that returns the current clap count:
function get_claps(){
  // Check if the file private/clap-count.txt exists
  if( file_exists(CLAP_FILE_NAME) ) {
    // It exists! Load the file to get the current value.
    // We use intval() to force it to be an integer (number):
    $claps = intval(file_get_contents(CLAP_FILE_NAME));
  } else {
    // It doesn't exist - treat it as being 0:
    $claps = 0;
  }
  return $claps;
}

// Check if the clap button was clicked:
if( $_POST['clap'] ) {
  // Get the current clap count:
  $claps = get_claps();

  // Add one to the claps count:
  $claps++;

  // Write the new count back to the file:
  file_put_contents(CLAP_FILE_NAME, $claps);

  // Redirect the user back to the same page to start over:
  header( 'Location: ' . $_SERVER['REQUEST_URI'] );
  die();
}

// Before we render the page, load the claps count:
$claps = get_claps();
?>

<p>
  Clap if you like this page!
</p>
<form method="post">
  <button type="submit" name="clap" value="true">
    👏<br>
    <?php echo $claps; ?>
  </button>
</form>