Jump to content

Archived

This topic is now archived and is closed to further replies.

marcus

Random text?

Recommended Posts

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

Share this post


Link to post
Share on other sites
Use the [url=http://www.php.net/file]file()[/url] function to read the file into an array and the [url=http://www.php.net/array_rand]array_rand()[/url] function to get a random line.

Ken

Share this post


Link to post
Share on other sites
uh, i'm stuck, havent learned those functions yet :P

Share this post


Link to post
Share on other sites
Read the manual pages that I gave the links to.

Ken

Share this post


Link to post
Share on other sites
All kinds of ways...

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

$file = './strings.txt';

$out = file ( $file );

shuffle ( $out );

echo trim ( $out[0] );

?>[/code]

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)

[code]000010
000010
clanks
tyrant
knifes
stoked
sieges
voodoo
hoaxed
calmed
lorded
beckon

[/code]

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

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

[code]<?

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 ();

?>[/code]

me!

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.