Search code examples
phpbuttoncounter

PHP click counter


I have a .php script that counts the clicks of a button and places them into a .txt file, all fine here but what I have now only works on a single count. If, let's say, I make two buttons, it will show the same number of clicks for both of them.

I need the script to work foreach button separately...

PHP:

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

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

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

HTML:

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="submit" value="click me!" name="clicks">
</form>
<div>Click Count: <?php echo getClickCount(); ?></div>

Solution

  • You should try different approach, I think. First, saving clicks in file is slower than in database, so you should use a database instead of file.

    Then, you can create a table, with button_id field and corresponding click_number field. So if button with id="1" is clicked you increment click_number value for that button.