nesiak Posted June 12, 2007 Share Posted June 12, 2007 How to get the list of all files in a specific folder an then randomize a number to choose one of them ? Quote Link to comment https://forums.phpfreaks.com/topic/55287-solved-random-file/ Share on other sites More sharing options...
smc Posted June 12, 2007 Share Posted June 12, 2007 For seeing the files and folders in a DIR see this: http://www.php.net/manual/en/function.scandir.php That will add the data to an array. From there I suppose you might be able to assign a number to each file in a foreach loop then have it randomly choose that file. //EDIT Perhaps something like this: <?php $dir = '/myteacups'; $myFiles = scandir( $dir ); $i = 1; foreach( $myFiles as $file ){ $var = "file" . $i //This will create us a var to store the address of the file name since number variable names aren't allowed $$var = $file; $i++; //This will now set up i for the next file } //Now that all the assignments are done lets do a random generation $random = rand( 1, $i ); //This will choose a random number from 1 to the number of files found in the array myFiles //And now lets assign the number to a variable we can use, and then send it to the my_file variable for echoing/downloading $var = "file" . $random; $my_file = $$var; ?> If you need me to explain further feel free to ask. Hope this helps Quote Link to comment https://forums.phpfreaks.com/topic/55287-solved-random-file/#findComment-273274 Share on other sites More sharing options...
nesiak Posted June 12, 2007 Author Share Posted June 12, 2007 Noup, tnx Quote Link to comment https://forums.phpfreaks.com/topic/55287-solved-random-file/#findComment-273289 Share on other sites More sharing options...
Psycho Posted June 12, 2007 Share Posted June 12, 2007 That needs be expanded on a bit as you will get directories listed in scandir(), as well as '.' and '..'. Here would be my solution: <?php $directory = "."; foreach(scandir('.') as $file_object){ if (!is_dir($file_object)) $fileArray[] = $file_object; } $random_file = $fileArray[array_rand ($fileArray)]; echo $random_file; ?> Quote Link to comment https://forums.phpfreaks.com/topic/55287-solved-random-file/#findComment-273292 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.