Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Block IPs for 24 hours

Tags:

php

ip

I have a PHP file that I want to collect people's IP's then prevent the PHP file from continuing if their IP has run the file within the last 24 hours. I've tried with cookies, but it kept giving me "can't change header" errors. Plus, people could just clear their cookies. Basically, it keeps the IP's of everyone who runs the php file, then if they try to access it within 24 hours it does "echo "You can access this again in 24 hours" and doesn't run the whole file. Then they can do it again after 24 hours.

like image 239
MOOcow102 Avatar asked Oct 09 '22 06:10

MOOcow102


2 Answers

Every time the page is viewed check if the ip address is in a database table after removing entries that are over 24 hours old

// Purge records
mysql_query("DELETE FROM ip_table WHERE access_date < DATE_SUB(CURDATE(), INTERVAL 24 HOUR)");

$ip = $_SERVER['REMOTE_ADDR'];
$result = mysql_query("SELECT ip FROM ip_table WHERE ip = '$ip'");
if($result){
  die("You can access this again in 24 hours");
} 
else {
  $result = mysql_query("INSERT INTO ip_table (ip, access_date) VALUES ('$ip', NOW())");
}

However, this will block all users using a shared connection. It is better to require a login, then block access per user.

like image 81
Pastor Bones Avatar answered Oct 14 '22 03:10

Pastor Bones


I think it would be much easier for you to have a table that stores the last access time for each ip, with a structure like:

Access

 - id          - int
 - ip_addr     - int
 - last_access - datetime

you transform from IP address in $_SERVER['SERVER_ADDR'] to an integer value with inet_pton(), and do a simple select in that DB table

like image 32
Tudor Constantin Avatar answered Oct 14 '22 04:10

Tudor Constantin