'PHP do something after 4 requests from same IP

Would it be possible via PHP to do something after a same IP address has accessed to the site for 4 times or more?

I can't use cookies as this rule needs to prevail even if using incognito mode or switching a browser if possible.

I managed to do it so it would show something after visiting more than 1 timed; but can't figure out how to achieve the specified before.

<?php
function allowedIP() {
    $vFile = 'vfile'; // file to store visitor data
    $revisit = 3600*24*60; // not allowed time in seconds
    $now = time(); // visit time
    $vIP = ip2long( $_SERVER['REMOTE_ADDR'] ); // get the ip and convert to long
    $vData = ( file_exists( $vFile ) ) ?
        unserialize( file_get_contents( $vFile ) ) : array(); // get the visit data
    if( ! isset( $vData[$vIP] ) || $now - $vData[$vIP] > $revisit ) {
        // first visit or 60 days passed since the first visit
        $vData[$vIP] = $now; // store the visit time
        file_put_contents( $vFile, serialize( $vData ) ); // save to file
        return true;
    }
    return false;
}

if( ! allowedIP() ) { ?>
<p>Paywall</p>
 <?php }

?>


Solution 1:[1]

Just create a new table with a column that stores ip records. Then create another column called counts or whatever with default value of 0. This will show how many times a user has visited your site.

Now create a simple query that checks if the ip exists in database. If the ip exists then update the counts column in ip table by adding it with 1. If it does not exist, add the ip and counts to 1.

Finally check if counts column contains value > 4 then do what you want!

NB: Different users might have the same ip address.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Snaville