I am counting the clicks on anchors and store the number of clicks in a .txt
file.
When click on an anchor, the number increases by 1.
I am not using a user management system, so to prevent multiple clicks on an anchor by a user, i need to store a cookie.
But i do have multiple anchors. If a user clicks on anchor 1, the number of click events on anchor 1 increases by 1. He should not have the possibility to click a second time on anchor 1, at least: it should not increase by 1 anymore.
But for that user, he still must be able to click on anchor 2 and anchor 3 and it should increase with 1. And after this, also these anchors should not increase by 1 anymore when user clicks on it.
How can i achieve this?
This is my html;
<?php
$clickcount = explode("
", file_get_contents('counter.txt'));
foreach($clickcount as $line){
$tmp = explode('||', $line);
$count[trim($tmp[0])] = trim($tmp[1]);
}
?>
<a href="#count" class="click-trigger" data-click-id="count1">Like</a>
<span class="click-count"><?php echo $count['count1'];?></span> likes.
<a href="#count" class="click-trigger" data-click-id="count2">Like</a>
<span class="click-count"><?php echo $count['count2'];?></span> likes.
<a href="#count" class="click-trigger" data-click-id="count3">Like</a>
<span class="click-count"><?php echo $count['count3'];?></span> likes.
The js:
$(document).on('click', '.click-trigger', function()
{
var data = {'id':$(this).attr('data-click-id')};
var count = $(this).next(".click-count");
$.ajax({
type : 'POST',
url : 'counter.php',
data : data,
success : function(data)
{
$(".click-count").fadeIn(500).show(function()
{
count.html(data);
});
}
});
return false;
});
And this is file counter.php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num
";
}
}
file_put_contents($file, $lines);
fclose($fh);
The file counter.txt
looks like this:
count1||36
count2||124
count3||12