2016-08-01 56 views
0

我需要創建一個從特定目錄返回隨機圖像或視頻的路線,我該如何實現?如何從特定文件夾返回一個隨機資產?

+2

我會使用'glob()'將目錄中的所有文件返回爲arr唉。在這一點上,你可以得到數組的長度,並使用'rand()'返回一個介於0和數組長度之間的隨機數。將它作爲數組索引插入,並從目錄中隨機選擇一個文件。 –

+0

您可以請upvote我的答案或接受它,如果它的工作。 –

回答

0

或許是這樣的

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; 

}); 

使用preg_grep而不是水珠的()。看到這樣的回答:https://stackoverflow.com/a/8541256/2468160

Tested

我的laravel版本是5.2.39,但我希望它能在5.1上工作。*

相關問題