如何在PHP重定向文件中实现IP每日/每小时一次访问限制?
Solution for IP-Based Hourly Redirect Restriction in PHP
Hey there! Let's build the PHP logic you need to limit specific IPs (like 192.168.1.1) to only one redirect to advertisement.php per hour. If they try again within the window, we'll either send them to a restriction page or show a friendly message.
Here's a tested, server-side solution using PHP sessions (tamper-resistant, no client-side cookie manipulation):
<?php // Start session to track visit history (stored server-side) session_start(); // Configuration - tweak these to match your needs $targetIP = '192.168.1.1'; // The specific IP to restrict $restrictionSeconds = 3600; // 1 hour in seconds (use 86400 for daily limit) $adRedirectURL = 'https://www.example.org/advertisement.php'; $restrictionRedirectURL = 'https://www.example.org/only-one-visit-per-hour-is-allowed.php'; // Get real user IP (handles proxies/Cloudflare scenarios) function getUserIP() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { return $_SERVER['HTTP_X_FORWARDED_FOR']; } else { return $_SERVER['REMOTE_ADDR']; } } $userIP = getUserIP(); // Check if we're targeting this user's IP if ($userIP === $targetIP) { // Check if a previous visit exists in the session if (isset($_SESSION['last_visit_time'])) { $currentTime = time(); $timeSinceLastVisit = $currentTime - $_SESSION['last_visit_time']; // If within restriction window, redirect to limit page if ($timeSinceLastVisit < $restrictionSeconds) { header("Location: $restrictionRedirectURL"); exit(); } } // No prior visit, or window has expired - update session and redirect to ad page $_SESSION['last_visit_time'] = time(); header("Location: $adRedirectURL"); exit(); } // Default behavior for non-target IPs (adjust as needed) header("Location: $adRedirectURL"); exit(); ?>
Key Customization Tips
- Switch to Daily Limit: Change
$restrictionSecondsto86400(24×60×60 seconds) to restrict visits to once per day instead of hourly. - Restrict Multiple IPs: Turn
$targetIPinto an array like['192.168.1.1', '10.0.0.5']and usein_array($userIP, $targetIP)instead of the strict equality check. - Show a Message Instead of Redirecting: Replace the restriction redirect block with this if you want to display text directly:
if ($timeSinceLastVisit < $restrictionSeconds) { echo "<h3>您最近已访问过本网站,请1小时后再来。</h3>"; exit(); }
内容的提问来源于stack exchange,提问作者Luis Cesar
相关产品推荐
相关产品推荐

