Reputation: 1913
I got inspired of this post to securely access files within my storage.
The post suggests to use the following route:
Route::get('file/{filename}', 'FileController@getFile')->where('filename', '^[^/]+$');
So I can access any file like http://yoursite.com/file/secret.jpg
Problem what if {filename}
contains a subfolder + filename
?
The url would look like http://yoursite.com/file/personal/secret.jpg
.
The route wouldn't be found.
I may also have many levels of subfolders.
Possible solution
As a temporary solution, I though of replacing http://yoursite.com/file/personal/secret.jpg
by http://yoursite.com/file/personal|secret.jpg
so {filename}
would be equal to personal|secret.jpg
. And in the getFile method, I would replace the |
by /
. But it looks like an ugly solution.
Is there a better solution for this?
Upvotes: 1
Views: 1360
Reputation: 35190
What you could do is define a pattern for that route param.
At the top of your routes file add:
Route::pattern('filename', '[a-zA-Z0-9.\-_\/]+');
Also, you will need to remove your where
clause for the Route:
Route::get('file/{filename}', 'FileController@getFile');
Hope this helps!
Upvotes: 5
Reputation: 1285
Even you can try regular expression in the where condition.
Something like this.
Route::get('file/{filename}', function ($filename) {
dd($filename);
})->where('filename', '^(.+)\/([^\/]+)$');
Tested and working with file/filename.jpg or file/files/files/filename.jpg etc.
Upvotes: 4