How can sessions be used to prevent spamming in PHP form submissions?

To prevent spamming in PHP form submissions, sessions can be used to track the number of times a form is submitted within a certain time frame. By setting a session variable to store the timestamp of the last form submission, the server can compare it to the current time and limit the number of submissions allowed. If the number of submissions exceeds a certain threshold, the server can block further submissions.

session_start();

if(isset($_SESSION['last_submit_time']) && time() - $_SESSION['last_submit_time'] < 10) {
    // Limit submissions to one every 10 seconds
    echo "You are submitting forms too quickly. Please try again later.";
    exit;
}

// Process form submission

// Update last submit time
$_SESSION['last_submit_time'] = time();