Laravel MySQL

Secure File Uploads in Laravel

Check file types and sizes, store them in the right place, and avoid the common pitfalls.

C Codesakura 1 min 0 comments

Contents

File uploads are a frequent entry point for security problems. Three things must be guarded: the file type, its size, and where it is stored.

Validate type and size

$request->validate([
  'document' => ['required', 'file', 'mimes:pdf,zip', 'max:5120'],
]);

Store outside the public folder

Files that should not be open to everyone go on a private disk, and are handed out by a controller that checks permissions.

$path = $request->file('document')->store('documents');

return Storage::download($path);

Never trust the file name from the user

Let Laravel generate a random name. Keep the original name in the database just for display.

Share X Facebook WhatsApp Telegram

0 comments

Log in to join the conversation. Log in

Related tutorials

Laravel

Building a REST API with Laravel from Scratch

1 min Series · Part 3 of 3

Laravel

Getting to Know Routing and Controllers in Laravel

1 min Series · Part 2 of 3

Laravel

Setting Up Your First Laravel Project

1 min Series · Part 1 of 3