What is the best practice for creating a button in PHP that increments a counter with each click?

To create a button in PHP that increments a counter with each click, you can use a session variable to store the counter value. Each time the button is clicked, you can increment the counter value in the session variable. This way, the counter will persist across page loads and increment correctly with each click.

<?php
session_start();

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

// Increment counter when button is clicked
if (isset($_POST['increment'])) {
    $_SESSION['counter']++;
}

?>

<form method="post">
    <button type="submit" name="increment">Increment Counter</button>
</form>

<p>Counter: <?php echo $_SESSION['counter']; ?></p>