1

I need to limit the access to a PHP web page for a user identified by IP address only 5 times a day.

I have done this funcionality with sessions, but in the requirements I have to that with IP Adresses abd not with sessions.

Any idea on the simplest method to do that?

Thanks a lot.

Bizboss
  • 7,792
  • 27
  • 109
  • 174
  • 1
    You may want to re-think those requirements. An IP address does not uniquely identify a user. One user can use many IP addresses to access your system, and many users can use one IP address. While there is definitely a place for limiting resources by IP, don't use it so broadly. – Brad Dec 09 '11 at 16:01
  • possible duplicate of [Limit Daily Access](http://stackoverflow.com/questions/5368419/limit-daily-access) – mario Dec 09 '11 at 16:01

4 Answers4

8

First, create a table with columns such as:

|-----------------------------------|
| IP varchar(15) | Views tinyint(1) |
|-----------------------------------|

Then on each view either insert the IP (if its not already in the database) or increment views by 1. If views = 5 then kill the page and don't allow the user to visit.

You can then run a cron each night at 00:00 that deletes all data in the table (see: truncate).

Prisoner
  • 27,391
  • 11
  • 73
  • 102
  • keep in mind that tinyint(1) has an upper limit of 127/255 (signed/unsigned) so if your needs ever change and you need more than that you'll need to adjust your field. – Tim G Dec 09 '11 at 16:44
3

On every access, save the IP address (UNIQUE field) into a database together with the current date/time and a counter. Increase the counter and update the date/time every access if the IP address already exixts in the database.

Now you can just deny acces when the counter is greater than 5 and date/time is not one day old.

However, consider what Brad said to you. IP address is not a reliable method to identify an user.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86
2

Building on Prisoner's answer:

I'd add a date field to this table and do an insert ... ON DUPLICATE KEY UPDATE

Bonus field: ip_log_page so you can use this on multiple pages.

you can also run a delete query based on the date to delete stuff from yesterday and before - either cron or just part of the script on a web page.

CREATE TABLE ip_log
(
    ip_log_ip VARCHAR(40),
    ip_log_date DATE,
    ip_log_visits TINYINT(1),
    ip_log_page varchar(255),
    PRIMARY KEY(ip_log_page,ip_log_ip,ip_log_date),
);

keep in mind that tinyint(1) has an upper limit of 127/255 (signed/unsigned) so if your needs ever change and you need more than that you'll need to adjust your field

Tim G
  • 1,812
  • 12
  • 25
0

You should look into apc cache or Zend cache to stored the IP that you'd get from $_SERVER['REMOTE_HOST']

JRL
  • 76,767
  • 18
  • 98
  • 146