How can PHP sessions be effectively used to prevent users from voting multiple times in a script?

To prevent users from voting multiple times in a script, you can use PHP sessions to track whether a user has already voted. When a user votes, store a flag in the session to mark that the user has voted. Before allowing a user to vote again, check if the flag is set in the session.

<?php
session_start();

// Check if user has already voted
if(isset($_SESSION['voted'])){
    echo "You have already voted.";
} else {
    // Process the vote
    echo "Thank you for voting!";
    
    // Set flag in session to mark user as voted
    $_SESSION['voted'] = true;
}
?>