What are some best practices for integrating a counter and redirect functionality in PHP scripts?

When integrating a counter and redirect functionality in PHP scripts, it is important to ensure that the counter increments before the redirect happens. This can be achieved by placing the counter increment code before the redirect code. Additionally, make sure to use proper conditional statements to control when the redirect should occur based on the counter value.

<?php
session_start();

// Initialize counter
if (!isset($_SESSION['counter'])) {
    $_SESSION['counter'] = 0;
}

// Increment counter
$_SESSION['counter']++;

// Check counter value and redirect if necessary
if ($_SESSION['counter'] >= 5) {
    header('Location: redirect_page.php');
    exit();
}
?>