genese
genese

Reputation: 23

Server Side Random Number Generator on a Website

I've got this website, see, and it currently generates a number every 5 minutes and generates a second smaller number every 5 seconds and adds that number to the first to give the illusion that the number is fluctuating. It might help to just see the website.

http://spinningcat.us/

It may seem silly, it's basically an inside joke.

Anyways, the problem is that as far as I know the number given is client side, and differs from person to person. Is it possible to make it server side? So that everybody that goes to the webpage at the same time will see the same number?

Thanks

Upvotes: 2

Views: 1917

Answers (2)

Schleis
Schleis

Reputation: 43700

You need to seed the random number generator so that php rand() function will return the same number to all visitors until the next random number is generated.

Use the current time from the server with time()

$fiveMinSeed = floor(time() / 300);
srand($fiveMinSeed);
$firstNumber = rand();


$fiveSecondSeed = floor(time() / 5);
srand($fiveSecondSeed);
$secondNumber = rand();

echo $firstNumber + $secondNumber;

This will generate two different seeds one based on the time that will change every 5 minutes and another that changes every 5 seconds. Then using those values you will get a 'random' number which will be the same for everyone until the seed changes.

You can use an AJAX request to get the number and display on your page.

http://php.net/manual/en/function.srand.php

NOTE:

If you are using mt_rand(), then you set the seed with mt_srand()

Upvotes: 2

user2652246
user2652246

Reputation:

You can use Ajax. Ajax sends a request to the server which will handle it and return a response without reloading the page. A good tutorial here.

EDIT: try this:

<script>
function loadXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET", "randomnumber.php");
xmlhttp.send();
}
setInterval(function(){loaxXMLDoc()},1000);
</script>

And in the PHP:

echo $randomNumber

(I'm not a PHP person so I don't know how to generate random numbers.)

Upvotes: 0

Related Questions