Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select random file from directory

Tags:

php

People also ask

How do I select random files in a folder?

On first run you select to add it to Windows Explorer and find that option available when you right-click in a folder in the file browser. There you find listed the new select random menu option. Selecting it picks a random file that is stored in the directory.

How do I select random files in file Explorer?

Click the first file or folder you want to select. Hold down the Shift key, select the last file or folder, and then let go of the Shift key. Hold down the Ctrl key and click any other file(s) or folder(s) you would like to add to those already selected.


You can use glob to get all files in a directory, and then take a random element from that array. A function like this would do it for you:

function random_pic($dir = 'uploads')
{
    $files = glob($dir . '/*.*');
    $file = array_rand($files);
    return $files[$file];
}

I've turned it a little to get more than one random file from a directory using array.

<?php

function random_pic($dir)
{
 $files = glob($dir . '/*.jpg');
 $rand_keys = array_rand($files, 3);
 return array($files[$rand_keys[0]], $files[$rand_keys[1]], $files[$rand_keys[2]]);
}

// Calling function

list($file_1,$file_2,$file_3)= random_pic("images"); 

?>

You can also use loop to get values.