Brian Lark's
This script finds/creates and reads/writes a file
File found!File reads: 27
Writting 28 to the file.
<?php
include('includes/header.php');
// Set error reporting for development environment
if ($_SERVER['ENV'] !== 'production') {
error_reporting(E_ALL);
ini_set('display_errors', 1);
} else {
error_reporting(0);
ini_set('display_errors', 0);
}
echo("<h1>Brian Lark's </h1>");
echo('<h2>This script finds/creates and reads/writes a file</h2>');
$counterFile = '../doc/count.txt';
// Function to read counter
function getCounter($counterFile) {
if (file_exists($counterFile)) {
$handle = fopen($counterFile, 'r');
$counter = (int) fread($handle, filesize($counterFile));
fclose($handle);
return $counter;
}
return 0; // Default value if file doesn't exist
}
// Function to write counter
function setCounter($counterFile, $counter) {
$handle = fopen($counterFile, 'w');
fwrite($handle, $counter);
fclose($handle);
}
// Check if file exists, if not, create it
if (!file_exists($counterFile)) {
echo('File is NOT there -- creating a new file. <br>');
setCounter($counterFile, 0); // Create file with 0 as the initial count
} else {
echo('File found! <br>');
}
// Get and display current counter
$counter = getCounter($counterFile);
echo("File reads: $counter<br>");
// Increment counter and update the file
$counter++;
setCounter($counterFile, $counter);
echo("Writting $counter to the file.<br>");
// Display the visit count
echo("<h3>This page has been visited $counter times.</h3>");
include('includes/footer.php');
?>