What are the best practices for handling user input, such as pressing the F5 key, in PHP scripts?

When handling user input in PHP scripts, it's important to validate and sanitize the input to prevent security vulnerabilities. To prevent users from causing unintended actions by pressing the F5 key (which triggers a page refresh), you can use session tokens or form submission tokens to ensure that the action is only performed once.

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['token']) {
        // Invalid token, do not process the request
        die('Invalid token');
    }

    // Process the form submission
    // ...
}

// Generate a new token for the form
$token = bin2hex(random_bytes(32));
$_SESSION['token'] = $token;
?>

<form method="post">
    <input type="hidden" name="token" value="<?php echo $token; ?>">
    <!-- Other form fields -->
    <button type="submit">Submit</button>
</form>