PhpSnip.com

User Stats

Pick up a random item from a file

Without loading the memory pick up a random item from a text file to display a random item e.g. Quotable quotes, a URL, address of a graphics file or even a code segment etc.

Info

 Download  View Source (print view)
 Rating : 4.7  Views : 227

Source Code ( 42 lines )

<?php

/*

Images.txt is a text file which can have any number of text lines like Quotable quotes, a URL, address of a  graphics file or even a code segment etc.to be randomly selected. Of course if the file is not in the same directory, correct path to be provided (sorry for the obvious sermon :) ).

You can edit Images.txt by adding deleting items as you wish. No more hard coding those damned Javascript arrays (YUCK!. It doesnt matter if there are 10 or 100 items - the code doesnt change as it dynamically selects the random item out of any number........wow

The $buffer at the end will have the magic random stuff that you can shove in any thing you want. YIKES!

I have just given an example and will come up with more in near future.

I have used some DHTML stuff in the example just for the heck of it. Its not a must. Thats why the need for 4.x browsers. But I guess all of you guys would have it.

*/
 

$fp = fopen ("images.txt", "r");
	if (!$fp) {
		echo "file cant be opened";
		exit();
	}
	$n = 0;
	while (!feof ($fp)) {
		$buffer = fgets ($fp, 4096);
		++$n;
	}
	--$n;
	srand ((double) microtime() * 1000000);
	$randno = rand(1, $n);
	rewind ($fp);
	$n = 0;
	while ($n < $randno) {
		$buffer = fgets ($fp, 4096);
		++$n;
	}
	$buffer = trim($buffer);
	fclose ($fp);

/* Code fragment ends here */

?>

Search

Subscribe

  Rss Feeds

Sponsors

Advertise