Jump to content

Random text?


marcus

Recommended Posts

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!
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...

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.