travis
travis

Reputation: 3

Is there a way to make this random URL redirect script not repeat the same URL more than once?

So I want to add a little bit of fun or "randomness" into a webpage, having a tab when clicked, redirect the user to a random URL. But, I want to make it where it doesn't repeat that URL if the user was just redirected to that.

So lets say user 1 clicks "random" and he is taken to http://google.com/ But then, he heads back to my page, and clicks on "random" a second time, I would like it to take him else where, and not back to http:/google.com/ It's fine if he is redirected to http://google.com/ if he goes back a 3rd time, but I just don't want it to repeat the same URL if they just visited that URL.

Is this doable in PHP the way I am describing it? Or is it more complex then I think it is?

This is currently what I am working with: (I ain't really PHP savvy at all, that's why I am asking).

<?php
$urls = array(
"www.google.com",
"www.youtube.com",
"www.facebook.com"
);
$url = $urls[array_rand($urls)];
header("Location: http://$url");
?>

Upvotes: 0

Views: 3083

Answers (1)

Philip G
Philip G

Reputation: 4104

You can do this by using sessions:

<?php
    session_start();

    function checkUrl($url, $urls){
        if(count($_SESSION['visited']) == count($urls)){
               $_SESSION['visited'] = Array();
        }
        if(in_array($url, $_SESSION['visited'])){
             $url = $urls[array_rand($urls)];
             checkUrl($url, $urls);
        }
        else{
             $_SESSION['visited'][] = $url;
             header("Location: http://$url");
        }
    }
    $urls = array(
        "www.google.com",
        "www.youtube.com",
        "www.facebook.com"
    );
    $url = $urls[array_rand($urls)];
    checkUrl($url, $urls);
?>

edit:

Implemented a reset when all adresses are visited

Upvotes: 1

Related Questions