Is it safe to store my asset on public folder laravel? my lecturer told me it wasn't safe, and he once told me there was a safer way than that. but I forgot what method to use, can anyone tell me?
CodePudding user response:
I got the same issue some days ago and came up with this solution:
First thing you have to do is upload the file to a non-public directory. My app is storing scanned invoices, so I'm going to place them inside storage/app/invoices. The code for uploading the file and generating the url would be:
// This goes inside your controller method handling the POST request.
$path = $request->file('invoice')->store('invoices');
$url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);
The url returned should result in something like http://yourdomain.com/storage/invoices/uniquefilename.jpg
Now you have to create a controller that uses the auth middleware to ensure the user is authenticated. Then, define a method that grabs the file from the private directory and returns it as a file response. That would be:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Storage;
class FileController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function __invoke($file_path)
{
if (!Storage::disk('local')->exists($file_path)) {
abort(404);
}
$local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;
return response()->file($local_path);
}
}
The last thing is register the route inside your routes/web.php file:
Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])
So there you have it, a pretty reusable snippet for all your projects that deals with private files :)
CodePudding user response:
I recommend using random file names for files stored publicly that should only be available in certain situations. This is essentially what is done by Laravel when using the File Storage API. See also in the official documentation.
When using random file names, images will only be available to users in situations defined by you (since you are the only one having access to the file names). I believe Laravel uses file names of length 40 so they can't really be guessed by anyone.