How can cookies be used to track user voting in a PHP survey?
Cookies can be used to track user voting in a PHP survey by setting a cookie when a user submits their vote. This cookie can store the user's vote and prevent them from voting again. When a user accesses the survey page, the PHP code can check for the presence of this cookie and display a message indicating that the user has already voted.
// Check if the user has already voted
if(isset($_COOKIE['voted'])){
echo "You have already voted in this survey.";
} else {
// Process the user's vote
$vote = $_POST['vote'];
// Save the user's vote in a cookie
setcookie('voted', $vote, time() + (86400 * 30), "/"); // Cookie expires in 30 days
// Display a thank you message
echo "Thank you for voting!";
}
Keywords
Related Questions
- How can one ensure that database queries in PHP scripts are executed successfully when switching servers, especially when encountering unexpected results?
- What are the advantages of using longer, commented code for beginners compared to shorter, more concise code?
- How can SQL WHERE comparisons be utilized to search for specific terms and redirect to corresponding images in PHP?