Jump to content

[SOLVED] Random file?


nesiak

Recommended Posts

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 

Link to comment
https://forums.phpfreaks.com/topic/55287-solved-random-file/#findComment-273274
Share on other sites

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;

?>

Link to comment
https://forums.phpfreaks.com/topic/55287-solved-random-file/#findComment-273292
Share on other sites

Archived

This topic is now archived and is 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.