PHP code review

Want to include a php script to generate a new word every new day.

Is this the correct way to do it?

<?php 

$file = fopen("interesting_words.txt","r");
$raw_string = fread($file,filesize("interesting_words.txt"));
fclose($file);
$words_array = explode("|",$raw_string);
echo $words_array[array_rand($words_array)]; 
srand(date("ymd"));

?>

My doubts is with the srand date format. Maybe I am wrong somewhere as it doesn’t change.

By the way, I wonder if the issue has to do with my location. I am in Spain, i.e. GMT +1

Any comment or help will be much appreciated.

Thanks

Mario Hussein

Well, first, the function srand() is to SEED-RANDOM-NUMBER-GENERATOR.

What this means is that it uses the clock or the number you insert as the start of the random numbers
that are returned when random functions are used. Therefore, you must use that command once in
your page and BEFORE you use any random functions.

Moving that above the echo command should solve you problems. Also, since PHP 4.2 this function is
no longer needed as the random generator functions self-seed. Using the line AFTER you use a random
function does nothing for you as this is a server-side command and does little on the server.

So, as long as you are using PHP 4.2 or higher, just drop the srand() line.

One minor issue with your routine is that you will sometimes get the same word two days in a row.
There are many ways to get around that but all require keeping track of the words previously used.
Sometimes it would be a list of maybe the last 50 you used and you would drop the first one and
add the latest word at the end. After 50 days, who cares… It’s hard to say depending on what you
need this for.

Hope that helps…

Sponsor our Newsletter | Privacy Policy | Terms of Service