PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]
Handling cookies and arrays with PHP
Working on my latest baby www.twitterknitter.co.uk one of the features was to add in a "like" tweet button. Catch - to prevent the user from liking if they had already liked.
Normally I would have used a db and sessions and closing down the browser and reopening would allow the user to like again.
This time I went for a cookie option so everytime a tweet was liked I would append that to the cookie so that the user was not able to vote unless they deleted that cookie.
The code segment is below (not the cleanest code):
<?php
$twitter_likes_ = array();
if(isset($_COOKIE['twitter_likes']))
{
//get the content from it
$already_voted_str = $_COOKIE['twitter_likes'];
//echo $already_voted_str . "
";
//get the string and convert into an array so that I can check to see if this entry_id is in there already
$already_voted_array = explode(",", $already_voted_str);
//print_r($already_voted_array);
//check that entry_id is not already in array
if(!in_array($entry_id, $already_voted_array))
{
//increment like count
$et->Update_likes();
//send back the total likes
$total_likes = ($et->Likes+1);
echo $total_likes;
//append the new entry_id to $already_voted_str
$already_voted_str = $already_voted_str . ",".$entry_id;
}
else
{
echo $et->Likes;
}
setcookie("twitter_likes", $already_voted_str, time()+(2592000)); /* expires in 1 month */
//echo "
Already votes string: ".$already_voted_str;
}
else
{
//increment like
$et->Update_likes();
//send back the total likes
$total_likes = ($et->Likes+1);
echo $total_likes;
setcookie("twitter_likes", $entry_id, time()+(2592000)); /* expires in 1 month */
}
?>
