Reputation: 83
This is a follow-up question from here.
The code is working great, it randoms the link to a blog post. The downside is that I may fall into the same post twice or too often.
header("Location: ".$posts[array_rand ($posts)][1]);
I need it to not fall on the same post more than once every 20 minutes, if runs out of posts then say: "Out of options. Come back in 20 minutes.". I tried doing it with cookies like so:
$rlink = $posts[array_rand ($posts)][1];
setcookie("rlink", "$rlink", time()+1200);
if ($rlink == $_COOKIE["rlink"]) {
header('Location: http://localhost/randommyblog.php');
} else
{
header("Location: ".$rlink);
}
It might be obvious that the problem here is that I'm replacing the cookie "rlink" every time, rendering the previous one useless.
Little help, please?
Upvotes: 1
Views: 210
Reputation: 140228
Try something like this, worked when I tested it as is:
$posts = array("hello", "world", "it's", "me" );
$len_posts = count( $posts );
$set_indices = @$_COOKIE['rlink'];
$rand = mt_rand( 0, $len_posts - 1 ); //Select a random index from the post
if( !empty( $set_indices ) )
{
$set_indices = array_map( "intval", explode( ",", $set_indices ) );
$len_indices = count( $set_indices );
if( $len_indices >= $len_posts )
{
die("no posts for you");
}
else
{
while( in_array( $rand, $set_indices, TRUE ) ) //Calculate a new index that has not been shown.
{
$rand = mt_rand( 0, $len_posts - 1 );
}
}
}
else
{
$set_indices = array();
}
array_push( $set_indices, $rand );
setcookie( "rlink", implode( ",", $set_indices ), time()+1200 ); //Set cookie of the shown indices like "3,0,1" for example.
echo $posts[$rand];
Upvotes: 2