Thursday, 17 October 2013

How to generate Random Numbers at Regular Intervals in PHP?

How to generate Random Numbers at Regular Intervals in PHP? 

Following is the simple PHP tutorial to demonstrate how to generate random numbers at regular intervals in PHP? I will use jquery setInterval() method for calling PHP file (which generates random numbers) at regular intervals say after every second in my example. I will use PHP rand() function to generate random numbers in PHP. I am using google CDN for jquery libraray. So here is the simple example in PHP to generate random numbers at regular intervals.

index.php file

<!DOCTYPE html>
<html lang="en">

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
var auto_refresh_random_numbers = setInterval(
function ()
{
$('#load_random_numbers').load('generate_random_numbers.php').fadeIn("slow");
}, 1000); // refresh random numbers after every 1000 milliseconds
});
</script>

</head>

<body>
<div id="load_random_numbers"> </div>
</body>

</html>

generate_random_numbers.php file

<?php
echo rand();
?>

So, that's all. Above PHP code snippet is very easy to understand by everyone. So, I don't think there is need of any explanation.

2 comments:

  1. And why would I want to do that? This post should be titled "How to poll a php script from JS in regular intervals" or something like that... You could at least explain different random number generators. For example for precision you should use mt_rand() instead of rand() ...

    ReplyDelete
  2. www.easyyar.com is a best jobs site, Search for Job Vacancies IT, Software, Govt., Technical and other jobs.Post your resume now and get your first dream job!

    http://www.easyyar.com

    ReplyDelete