Jump to content


Photo

Random text?


  • This topic is locked This topic is locked
5 replies to this topic

#1 marcus

marcus
  • Members
  • PipPipPip
  • Advanced Member
  • 1,842 posts
  • LocationRochester, NY

Posted 07 October 2006 - 05:27 PM

How would I go about and making random text appear on a website while using a .txt file to pick from it.

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 07 October 2006 - 05:32 PM

Use the file() function to read the file into an array and the array_rand() function to get a random line.

Ken

#3 marcus

marcus
  • Members
  • PipPipPip
  • Advanced Member
  • 1,842 posts
  • LocationRochester, NY

Posted 07 October 2006 - 05:33 PM

uh, i'm stuck, havent learned those functions yet :P

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 07 October 2006 - 05:33 PM

Read the manual pages that I gave the links to.

Ken

#5 printf

printf
  • Staff Alumni
  • Advanced Member
  • 889 posts

Posted 07 October 2006 - 05:47 PM

All kinds of ways...

not resource friendly, if you have a big file...
<?

$file = './strings.txt';

$out = file ( $file );

shuffle ( $out );

echo trim ( $out[0] );

?>

Resource friendly way, for big files...

1. assign each line a set length, like ( 500 characters)
2. place the total number of lines that are in the file on line (1)
3. place the current counter of the next random line to read on line (2)

Then you read + write using fseek(), so every next request is really random!

I'll give a simple example, for something like form protection (Captcha), where you might want the security word to be a real word, not some random word

1. create a file 'words.txt' like so... (example is short, but you can have thousands of words)

000010
000010
clanks
tyrant
knifes
stoked
sieges
voodoo
hoaxed
calmed
lorded
beckon


Then to use it, you could use this simple function...

// note if on Unix / Linux / Mac, change $data = 8; to $data = 7;

<?

function get_word ()
{
	$file = './words.txt';
	$word = 6;
	$data = 8;

	$io = fopen ( $file, 'r+' );

	while ( flock ( $io, LOCK_EX ) === false )
	{
		usleep ( 1000 );
	}

	$size = intval ( fread ( $io, $data ) );
	$line = intval ( fread ( $io, $data ) );

	if ( $line == 2 )
	{
		$line = $size;
	}

	fseek ( $io, ( ( $line * $data ) - $data ) );

	$out = rtrim ( fread ( $io, $data ) );

	fseek ( $io, $data );

	fputs ( $io, sprintf ( '%0' . $word . 'd', ( $line - 1 ) ) );

	fclose ( $io );

	return ( $out );
}

echo get_word ();

?>

me!

#6 marcus

marcus
  • Members
  • PipPipPip
  • Advanced Member
  • 1,842 posts
  • LocationRochester, NY

Posted 07 October 2006 - 05:51 PM

Awesome, thanks!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users