Don Alexander Eckford's Hit-Counter:
This script finds/creates and reads/writes a file
File found!File is readable -- reading the file.
File reads: 34
File is writable -- writing the file.
Writing 35 to the file.
<?php
// Include the header file (assumed to contain common HTML and styles)
include('includes/header.php');
// Enable error reporting to display all errors (useful for debugging)
error_reporting(E_ALL);
echo("<h1>Don Alexander Eckford's Hit-Counter:</h1>");
echo('<h2>This script finds/creates and reads/writes a file</h2>');
// Path to the counter file (relative path)
$counterFile = '../docs/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>');
// Attempt to create a new counter file
$handle = fopen($counterFile, 'w') or die('Could not create file.');
fwrite($handle, '0'); // Initialize the counter to 0
fclose($handle); // Close the file handle
}
// Open the counter file for reading
$handle = fopen($counterFile, 'r');
if ($handle)
{
echo('File is readable -- reading the file. <br>');
// Read the contents of the counter file, cast to an integer
$counter = (int) fread($handle, filesize($counterFile));
fclose($handle); // Close the file handle after reading
echo("File reads: $counter<br>");
}
else
{
echo("Cannot read the $counterFile ! <br>");
exit(); // Exit if file cannot be read
}
// Open the counter file for writing
$handle = fopen($counterFile, 'w');
if ($handle)
{
echo('File is writable -- writing the file. <br>');
$counter++; // Increment the counter
// Write the incremented counter value to the file
fwrite($handle, $counter);
fclose($handle); // Close the file handle after writing
echo("Writing $counter to the file.<br>");
}
else
{
echo("Cannot write to the $counterFile !");
exit(); // Exit if file cannot be written to
}
// Display the counter value, which represents the number of visits
echo("<h3>This page has been visited $counter times.</h3>");
// Include the footer file (assumed to contain closing HTML and scripts)
include('includes/footer.php');
?>