Hello just question i have shortlink website and i need add limit visit by ip
example: if one ip visit my shortlink 5 times today and visit it again He receives a message: You have exceeded the number of daily visits. Come back tomorrow
Thanks
I tried doing the following and it didn’t work
CREATE TABLE `ip_visits` (
`ip_address` varchar(255) NOT NULL,
`visits` int(11) NOT NULL DEFAULT '0',
`last_visit` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ip_address`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I created a PHP function that limits link visits to 5 times per day from one IP address
<?php
function check_ip_limit($ip_address) {
$max_visits = 5;
$time_period = "24 hours";
$current_time = new DateTime();
$yesterday = $current_time->sub(new DateInterval('P1D'));
// Get the number of visits for the IP address within the time period
$visits = get_visits_from_db($ip_address, $yesterday);
// If the number of visits is greater than or equal to the maximum visits, return true
if ($visits >= $max_visits) {
return true;
}
// If the number of visits is less than the maximum visits, update the visits and return false
update_visits_in_db($ip_address);
return false;
}
function get_visits_from_db($ip_address, $yesterday) {
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $db->prepare("SELECT visits FROM ip_visits WHERE ip_address = :ip_address AND last_visit >= :yesterday");
$stmt->bindParam(':ip_address', $ip_address);
$stmt->bindParam(':yesterday', $yesterday->format('Y-m-d H:i:s'));
$stmt->execute();
$visits = $stmt->fetchColumn();
return $visits;
}
function update_visits_in_db($ip_address) {
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $db->prepare("UPDATE ip_visits SET visits = visits + 1, last_visit = NOW() WHERE ip_address = :ip_address");
$stmt->bindParam(':ip_address', $ip_address);
$stmt->execute();
}
// Example usage:
$ip_address = $_SERVER['REMOTE_ADDR'];
if (check_ip_limit($ip_address)) {
echo "You have exceeded the daily visit limit for this link.";
} else {
// Allow the user to visit your link
}
?>
New contributor
Ksomar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.