Magic Coding
Magic Coding

Reputation: 5

How do I count unique visitors to my web page and recount the counter everyday without using database?

How do i count unique visitors to my web page using php and recount the counter everyday (24 h)?

Also, i need to save the number of visitors on text file. i don't need to use database.

This is what i try and its sample code to get user ip and count +1:

<?php

$ip = $_SERVER['REMOTE_ADDR'];
$count = file_get_contents("counter.txt");
$count = trim($count);
$count = $count + 1;
$fl = fopen("counter.txt","w+");
fwrite($fl,$count);
fclose($fl);

echo $ip;

?>

Upvotes: 0

Views: 1052

Answers (1)

dlporter98
dlporter98

Reputation: 1630

<?php

    $filename = date("Ymd") . "_counter.txt";
    $seenFilename = date("Ymd") . '_seen_ip.txt';

    $ips = array();
    if (file_exists($seenFilename))
    {
        $ips = file($seenFilename);
        $ips = array_map('trim', $ips);
    }

    if(!in_array($_SERVER['REMOTE_ADDR'], $ips))
    {
        $visits = 0;
        if (file_exists($filename)) {
            $visits = file_get_contents($filename);
        }


        file_put_contents($filename, ++$visits);
        $data = $_SERVER['REMOTE_ADDR'] . PHP_EOL;
        $fp = fopen($seenFilename, 'a');
        fwrite($fp, $data);
    }

?>

This code will create a new file every day and record one count for each unique visit.

Upvotes: 1

Related Questions