Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo clicks count on php button click counter

Tags:

php

I found this script in php which counts button clicks and saves them to a txt file.

 <?php
    if( isset($_POST['clicks']) )
    { 
        clickInc();
    }
    function clickInc()
    {
        $count = ("clickcount.txt");

        $clicks = file($count);
        $clicks[0]++;

        $fp = fopen($count, "w") or die("Can't open file");
        fputs($fp, "$clicks[0]");
        fclose($fp);

        echo $clicks[0];
    }
    ?>

    <html>

        <head>

           <title>button count</title>

        </head>
        <body>
            <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
                <input type="submit" value="click me!" name="clicks">
            </form>

        </body>
    </html>

what i cant figure out is how to echo the number of button clicks to a different part of the html. i've tried placing:

 <?php
     echo $clicks[0];
 ?>

but that does not work. what am i doing wrong? thanks..

like image 950
fafchook Avatar asked Apr 17 '26 02:04

fafchook


1 Answers

I'd suggest separating the part of the code that reads the click count from the part that increments it, so that you can call each part on it's own. Then you don't have to save the click count from the actual incrementation part; you could get the click count on it's own whenever needed, exactly as it exists in the file at that point in time.

if( isset($_POST['clicks']) ) { 
    incrementClickCount();
}

function getClickCount()
{
    return (int)file_get_contents("clickcount.txt");
}

function incrementClickCount()
{
    $count = getClickCount() + 1;
    file_put_contents("clickcount.txt", $count);
}

With that, you could include the current count at any point in your HTML, by calling the getClickCount function.

    <div>Click Count: <?php echo getClickCount(); ?></div>
</body>
like image 150
Atli Avatar answered Apr 18 '26 17:04

Atli