Steph's Hit-Counter:

This script finds/creates and reads/writes a file

File found!
File is readable -- reading the file.
File reads: 19
File is writable -- writing the file.
Writing 20 to the file.

This page has been visited 20 times.

<link rel="stylesheet" href="../css/assignmentHeaderStyles.css" />
<?php
include('../header/assignmentHeader.php');

error_reporting(E_ALL);

// Display page title
echo "<h1>Steph's Hit-Counter:</h1>";

echo 
"<h2>This script finds/creates and reads/writes a file</h2>";

// Counter file location
$counterFile = '../doc/count.txt';

// Check if the counter file exists
if (file_exists($counterFile)) {
    echo 
"File found!<br>";
} else {
    echo 
"File is NOT there -- creating a new file.<br>";

    
// Create a new counter file
    
$handle = fopen($counterFile, 'w')
    or die(
'Could not create file.');

    
fwrite($handle, '0');
    
fclose($handle);
}

// Read the counter file
$handle = fopen($counterFile, 'r');

if (
$handle) {
    echo 
"File is readable -- reading the file.<br>";

    
// Read the current counter value
    
$counter = (int) fread($handle, filesize($counterFile));

    
fclose($handle);

    echo 
"File reads: $counter<br>";
} else {
    echo 
"Cannot read the $counterFile!<br>";
    
$counter = 0;
}

// Write the updated counter
$handle = fopen($counterFile, 'w');

if (
$handle) {
    echo 
"File is writable -- writing the file.<br>";

    
// Increment the counter
    
$counter++;

    
// Save the new counter value
    
fwrite($handle, $counter);

    
fclose($handle);

    echo 
"Writing $counter to the file.<br>";
} else {
    echo 
"Cannot write to the $counterFile!";
}

// Display the final counter
echo "<h3>This page has been visited $counter times.</h3>";

// Display the PHP source code
show_source(__FILE__);

include(
'../footer/footer.php');
?>