Austin's Hit-Counter:

This script finds/creates and reads/writes a file

File found!
File is readable -- reading the file.
File reads: 75
File is writeable -- writing the file.
Writting 76 to the file.

This page has been visited 76 times.


Code follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hit Counter</title>
    <link rel="stylesheet" href="../css/styles.css">
</head>
<body>

<div class="page">

    <p class="nav"><a href="../../index.php">Home</a></p>

    <?php
    error_reporting
(E_ALL);    // set error reporting to all
    
ini_set('display_errors', 1);    // ADDED: show errors on the page

    
echo("<h1>Austin's Hit-Counter:</h1>");

    echo(
'<h2>This script finds/creates and reads/writes a file</h2>');

    
$counterFile = '../doc/count.txt';
    
$counter = 0;    // ADDED: so the variable always exists
    
if (!is_dir(__DIR__ . '/../doc')) {
        
mkdir(__DIR__ . '/../doc', 0755);
    }

    if(
file_exists($counterFile))        // does file exist?
    
{
        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);
    }

    
$handle = fopen($counterFile, 'r');    // try reading the file
    
if($handle)
    {
        echo(
'File is readable -- reading the file. <br>');

        
// read the contents of the counter file
        
$counter = (int) fread($handle, 20);
        
fclose($handle);
        echo(
"File reads: $counter<br>");
    }
    else
    {
        echo(
"Cannot read the $counterFile ! <br>");
    }

    
$handle = fopen($counterFile, 'w');    // try writting the file
    
if($handle)
    {
        echo(
'File is writeable -- writing the file. <br>');
        
$counter++;        // increment the counter

        // write the new value of the counter to the file
        
fwrite($handle, $counter);
        
fclose($handle);
        echo(
"Writting $counter to the file.<br>");
    }
    else
    {
        echo(
"Cannot write to the $counterFile !");
    }

    echo(
"<h3>This page has been visited $counter times.</h3>");
    
?>



    <hr>

    <h2>Code follows</h2>

    <div class="code"><?php highlight_file(__FILE__); ?></div>

    <p class="nav nav-foot"><a href="../../index.php">Home</a></p>

</div>

</body>
</html>