jSherz
jSherz

Reputation: 927

Storing Record for IP Address (DB Alternative)

I need to store a record for a user per IP address to limit the rate at which a certain IP address can perform an action.

I know that storing the IP in a database would work but I am worried that on a small VPS with limited resources, too much processing power would be taken by the MySQL process. Is there another way of storing data for an IP?

I thought of a system similar to:

/ips/
/ips/127/
/ips/127/0
/ips/127/0/0
/ips/127/0/0/1.txt

Sample Code:

$ip_parts = explode('.', $_SERVER['REMOTE_ADDR']);
$records = intval(file_get_contents('ips/' . implode('/', $ip_parts)));

if($records > 50) {
    echo 'Error - credits used.';
} else {
    // Do something
}

With the 1.txt file containing the needed data. Would I encounter issues with the number of files or folders causing this method to be slower than a database?

Upvotes: 0

Views: 334

Answers (4)

WWW
WWW

Reputation: 9870

Check out this question / answer on ServerFault regarding DBMS optimization. You're trying to reinvent the wheel for no particular reason (unless you won't ever use MySQL on that VPS). And, while on the subject of storing IP addresses in MySQL, take a look at the INET_ATOI() function for MySQL.

Upvotes: 2

nikc.org
nikc.org

Reputation: 16993

Using a filesystem is not free either and can cause a lot of gray hair on multiple points, so I'm skeptic as to whether it would actually be better than using a database.

That said, whether you end up using files or a database, you would probably want to learn about ip2long and MySQL's equivalent INET_ATON. Especially if you end up using MySQL, since numeric keys tend to be more efficient than strings.

Upvotes: 1

kba
kba

Reputation: 19476

What makes you think building your own file-based database scheme is better than software build for the purpose by software engineers with 20 years of experience? Just use a MySQL database - there's rarely a case where not doing so is better - other than if you actually wish to save files.

Upvotes: 3

Calgoo
Calgoo

Reputation: 1

Have you tried sqlite? It should work well.

http://php.net/manual/en/book.sqlite.php

Upvotes: 0

Related Questions