marcus Posted October 7, 2006 Share Posted October 7, 2006 How would I go about and making random text appear on a website while using a .txt file to pick from it. Link to comment Share on other sites More sharing options...
kenrbnsn Posted October 7, 2006 Share Posted October 7, 2006 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 Link to comment Share on other sites More sharing options...
marcus Posted October 7, 2006 Author Share Posted October 7, 2006 uh, i'm stuck, havent learned those functions yet :P Link to comment Share on other sites More sharing options...
kenrbnsn Posted October 7, 2006 Share Posted October 7, 2006 Read the manual pages that I gave the links to.Ken Link to comment Share on other sites More sharing options...
printf Posted October 7, 2006 Share Posted October 7, 2006 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 word1. create a file 'words.txt' like so... (example is short, but you can have thousands of words)[code]000010000010clankstyrantknifesstokedsiegesvoodoohoaxedcalmedlordedbeckon[/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 More sharing options...
marcus Posted October 7, 2006 Author Share Posted October 7, 2006 Awesome, thanks! Link to comment Share on other sites More sharing options...
Recommended Posts