user6918165
user6918165

Reputation:

Random HTML page redirect

So what I'm trying to do is have it so when you are on one of my webpages, there is a small chance to be randomly redirected to another page. Like 1 in 500 chance. Is this even possible? Please help.

Upvotes: 3

Views: 10757

Answers (4)

Michael Nealon
Michael Nealon

Reputation: 76

This could be done easily in javascript.

Just get a random number between 0 and 500, let's say if the random number is 0 then we redirect the user to another page, otherwise we don't.

<script>
    var randNum = Math.floor(Math.random() * 500);

    if (randNum == 0)
        window.open('redirect-url', '_self');
</script>

If you want to redirect the user to a random website from a list of websites you can do something like this:

<script>
    // get a random number between 0 and 499
    //
    var randNum = Math.floor(Math.random() * 500);

    // An array of URL's
    var randURLs = [
        "http://url0",
        "http://url1",
        "http://url1"
    ];

    // There was a 1 in 500 chance we generated a zero.
    if (randNum == 0) {
        // randURLs.length will tell us how many elements are
        // in the randURLs array - we can use this to generate
        // a random number between 0 and n (number of elements)
        //
        // In our case there are 3 elements in the array, 0, 1
        // and 2. So we want to get another random number in
        // the inclusive range 0 - 2
        //
        var randURL = Math.floor(Math.random() * randURLs.length);

        window.open(randURLs[randURL]);
    }
</script>

Upvotes: 3

Falk
Falk

Reputation: 637

Here is what I meant in the comment:

var test = Math.floor(Math.random() * 500) <= 1;

if (test) {
    window.location = "http://www.yoururl.com";
}

Upvotes: 1

Umair Khan
Umair Khan

Reputation: 307

Yes, if you do the following:

var redirect = [/*500 different pages with "" around each and each separated by , outside ""*/]

window.location.href = redirect[Math.floor(Math.random() * 500)]

Upvotes: 2

user2488619
user2488619

Reputation:

Yes. you can use this function, it has a chance of 1 in 500:

<?php 
    if (rand(0,500)==250) 
         random_redirect();
    random_redirect(){
    header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */}
?>

OR in javascript:

var rand = Math.floor((Math.random()*500)+1);
if ( rand==250){
    window.location = "http://www.yoururl.com";}

Upvotes: 1

Related Questions