Friday, March 3, 2017

Unique IP Counter with Laravel and MySQL

I'm trying to make a simple Unique IP counter for gallery page views.

The idea I have is to keep the views records separate from the image records in 2 tables.

Database Tables

gallery

Holds Image: id, name, category, views columns

gallery

unique_ips

Holds a visitor ip for the Image name viewed

This example screenshot shows 3 visitors each viewing 3 images. I used free proxy ips.

unique_ips

View Counter

If New IP detected:

Add name+ip to unique_ips.
Increment gallerynameviews +1.

$name = "Image 1";
$ip = getenv('REMOTE_ADDR');

// Increment Views if New IP visitor
// Proceed if name + ip record does not exist in table
if (!DB::table('unique_ips')->where('name', '=', $name)->where('ip', '=', $ip)->exists()) { 

    // Add Name/IP Record
    DB::table('unique_ips')->insert([
        ['name' => $name, 'ip' => $ip]
    ]);

    // Views +1 
    DB::table('gallery')
        ->where('name', $name)
        ->increment('views', 1);
}

Problem

This view counter works, but all unique ip records are grouped together under 2 columns. It would have to search through all records to find a match, which might slow down with thousands of ip's.

Other Ideas

  1. Use only the gallery table and add a unique_ips column, which would hold an array of ip's. But how many could it hold if string/text is limited to a number of characters?

  2. Each name could have it's own Column containing ip's. But then I'd have thousands of Columns.

  3. I could store ip's in name text files instead of in the database.

Is there a better way to design this?



via Matt McManis

Advertisement