0

I need to create a route where a random image or video is returned from a specific directory, how can I achieve this?

Caio Kawasaki
  • 2,894
  • 6
  • 33
  • 69
  • 2
    I would use `glob()` to return all of the files in the directory as an array. At which point you could get the length of the array and use `rand()` to return a random number between 0 and the array length. Plug that in as the array index and you've got a randomly selected file from a directory. – Kirk Logan Aug 01 '16 at 14:36
  • Could you please upvote my answer or accept it if it worked. – P_95 Apr 04 '17 at 06:29

1 Answers1

0

perhaps something like this

Route::get('/random_media/', function() {

    // Get random files and pick one.
    $folder_path = public_path()."/your/path/here/"; // in my test case it's under /public folder
    $files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($folder_path));
    $randomFile = $files[array_rand($files)]; // if 5 files found, random int between 0 and 4
    // Display it
    $file = File::get($folder_path.$randomFile);
    $response = Response::make($file, 200);
    $response->header('Content-Type', mime_content_type($folder_path.$randomFile));
    return $response;

});

Using preg_grep instead of glob(). see this answer: https://stackoverflow.com/a/8541256/2468160

Tested

My laravel version is 5.2.39, but I hope it works on 5.1.*

Community
  • 1
  • 1
P_95
  • 145
  • 8