How can a counter be added to limit the number of page refreshes in PHP?

To limit the number of page refreshes in PHP, you can use a session variable to keep track of the number of refreshes. Each time the page is refreshed, increment the counter stored in the session variable. Once the counter reaches a certain limit, you can redirect the user to a different page or display an error message.

<?php
session_start();

// Check if the session variable exists
if (!isset($_SESSION['refresh_counter'])) {
    $_SESSION['refresh_counter'] = 1;
} else {
    $_SESSION['refresh_counter']++;
}

// Set the maximum number of refreshes allowed
$max_refreshes = 5;

// Check if the refresh limit has been reached
if ($_SESSION['refresh_counter'] > $max_refreshes) {
    // Redirect to a different page or display an error message
    header('Location: error_page.php');
    exit;
}
?>