PHPBuilder - QuoteMaster



RSS Twitter
Snippets Other

QuoteMaster

by: Roger Bailey
|
September 18, 2002

Version: 2.0

Type: Full Script

Category: Other

License: GNU General Public License

Description: This program reads quotes from a text file, and then prints one randomly each time a page is loaded.



// Version 1.0 is really inefficient since it reads the whole file into an array.

// This version dives into a random position in the file, it reads two strings since the first is lilely to be only a partial line, if it hit EOF then it wraps to the begining.  

// Get a random quote.
$file = "./Common/Quotes.txt";
if(!file_exists($file) || !($fp = fopen($file, "r")))
{
	die("Unable to open file $file.");
}

// Seek to random position in the file.
$size = filesize($file);
srand((double)microtime()*1000000);
$randval = rand(0, $size);
fseek($fp, $randval);

// Throw away partial line.
$quote = fgets($fp, 1024);

// Read next whole line.
$quote = trim(fgets($fp, 1024));

// If EOF wrap to begining of file.
if(empty($quote))
{
	fseek($fp, 0);
	$quote = trim(fgets($fp, 1024));
}  
fclose($fp);

// Print the quote.
print("Random quote - \"$quote\"");

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Roger Bailey

Comment:



Comment:

(Maximum characters: 1200). You have characters left.