Skip to content
PHP Logo

How can PHP be used to detect and restrict the number of visitors on a website at a given time?

To detect and restrict the number of visitors on a website at a given time using PHP, you can implement a session-based counter that increments each time a new visitor accesses the website. Once the maximum number of visitors is reached, you can redirect additional visitors to a custom error page or display a message indicating that the website is currently at capacity.

php
session_start();

// Set the maximum number of visitors allowed
$maxVisitors = 100;

// Increment the visitor counter
if (!isset($_SESSION['visitor_count'])) {
    $_SESSION['visitor_count'] = 1;
} else {
    $_SESSION['visitor_count']++;
}

// Check if the maximum number of visitors has been reached
if ($_SESSION['visitor_count'] > $maxVisitors) {
    header("Location: error_page.php");
    exit;
}