Last updated: 18 November 2026. Every behavior below was run on Laravel 13.40, PHP 8.3 and a local disk. SeeHow this was checkedfor what was not covered.
An upload form is an invitation to send your server arbitrary bytes under a name of the sender's choosing. Most Laravel upload bugs come from trusting one of those two things: the file name or the file content. Validation helps with the first and partly with the second, but it cannot make hostile content safe. The part that decides whether an upload becomes an incident is where you store the file and how you serve it back.
This article follows an upload through three stages (validate, store, serve) and shows what each Laravel rule actually checks, using real test files.
What you are defending against
| Attack | What it relies on | Main defense |
|---|---|---|
Executable disguised by name (shell.php.jpg) | You keep the client's name and the server runs it | Generated names, no execution in upload paths |
| Wrong content with a harmless extension | You check only the extension | Validate the content type |
| Valid image with code appended (polyglot) | You store the original bytes | Re-encode images, never execute uploads |
| SVG with a script | You serve it inline from your domain | Block SVG or serve as a download |
Path tricks (../../) | You build the path from the client's name | Never use the client's name in a path |
| Oversized files | No limits at any layer | Limits in validation, PHP and the web server |
| Reading someone else's file | Public, guessable URLs | Private disk plus an authorized route |
Stage 1: validate, and know what each rule checks
I ran the same set of hostile files through the validation rules. Each file is a real file on disk wrapped as an uploaded file, with a client-chosen name. Results:
| Test file | Rule | Result |
|---|---|---|
Real PNG named photo.png | image, max:2048 | Pass |
PHP source named evil.jpg | image | Fail, even when the client claims image/jpeg |
PHP source named evil.jpg | extensions:jpg | Pass |
PHP source named evil.jpg | File::types(['jpg']) | Fail |
Real PNG bytes named evil.php | image | Fail |
Real PNG bytes named evil.php.png | image | Pass |
Valid PNG with PHP code appended, named x.png | image | Pass |
| SVG containing a script tag | image | Fail |
| Same SVG | image:allow_svg | Pass |
Reading the Laravel 13 source explains the pattern:
-
mimes,imageandFile::types()look at the file's content: they callguessExtension(), which detects the type from the bytes. The Laravel docs say the same: the content is read and the type guessed, which may differ from what the client provided. -
mimesandextensionsalso refuse files whose client-supplied extension is a PHP one (php,phtml,pharand a few others), unless you listphpyourself. -
extensionscompares only the client-supplied extension. It never opens the file, which is why the PHP source passed it. Use it as an additional naming rule, never as the only check. -
imageexcludes SVG by default; the docs give the XSS risk as the reason. You must opt in withimage:allow_svg.
The two that matter most for your threat model are the passing ones. A file named evil.php.png is a valid PNG as far as validation is concerned, and so is a PNG with PHP appended. Validation answers "does this look like a PNG", not "is this safe to put on a server that runs PHP". That is the job of the next two stages.
A reasonable form request:
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; use Illuminate\Validation\Rules\File; class UpdateAvatarRequest extends FormRequest { public function rules(): array { return [ 'avatar' => [ 'required', File::image() // jpg, png, gif, bmp, webp, avif, heic, heif; no SVG ->max('2mb') ->dimensions(Rule::dimensions()->maxWidth(4000)->maxHeight(4000)), ], ]; } } For documents, name the types you accept: File::types(['pdf'])->max('10mb'). A list of allowed types beats a list of blocked ones.
Stage 2: store with a name you generated
Do not build a path from getClientOriginalName(). It is attacker-controlled text. I fed in a file called ../../etc/evil.php.png; Laravel reduced the client name to evil.php.png, and store() ignored it entirely:
$path = $request->file('avatar')->store('avatars'); // avatars/FzWsgNcTQ4ed8QZ3NMlOS4Eyxfx7Duc3dXf0AXRe.png store() generates a 40-character random name and takes the extension from the guessed content type, not from the client. Two more results from my run:
- A text file named
notes.txtwas stored asdocs/<random>.txt. - A PHP source file named
evil.php(which would normally fail validation) was stored asdocs/<random>with no extension at all because the content type was not recognized as a known extension.
The generated name stops path tricks and removes guessable URLs. It does not change the bytes. The polyglot PNG was stored untouched, 92 bytes, with the PHP code still inside. That is harmless as long as nothing ever executes it, so:
- Store uploads on a private disk. In a standard Laravel 13 app the default
localdisk lives understorage/app/private, outsidepublic/. Nothing is reachable by URL until you add a route for it. - Keep uploads out of anywhere PHP is executed. With a standard Laravel layout only
public/index.phpshould be run by PHP. If you usephp artisan storage:linkto expose apublicdisk, check that your web server config does not hand every.phppath to PHP-FPM, since that link lands user content under the web root. I did not test web server configurations. - Store the generated path in your database and the original name as a separate display-only column.
On a bare local disk, I observed directory permissions 0700 and file permissions 0644. Set visibility and directory_visibility on the disk if you need different modes; the docs describe private as 0600 for files and 0700 for directories.
Re-encode images instead of trusting them
For avatars and similar, decode the image and write a fresh file. Anything that is not pixel data does not come along. I ran this on a PNG with PHP code appended: the input was 86 bytes and contained <?php, the re-encoded output was 90 bytes and did not. Feeding it plain PHP text made imagecreatefromstring return false.
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; $image = @imagecreatefromstring($request->file('avatar')->get()); if ($image === false) { abort(422, 'The file is not a readable image.'); } ob_start(); imagepng($image); $png = ob_get_clean(); $path = 'avatars/'.Str::random(40).'.png'; Storage::put($path, $png); This needs the GD extension (present in my environment). It converts everything to PNG, drops metadata such as EXIF, and loses animation in GIFs, so pick the output format to suit your use case. Libraries like Intervention Image do the same job with more formats; I did not test one.
Stage 3: serve files deliberately
A private file needs a route, and the route is where you do authorization:
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Storage; Route::get('/avatars/{avatar}', function (Avatar $avatar) { Gate::authorize('view', $avatar); return Storage::response( $avatar->path, null, ['X-Content-Type-Options' => 'nosniff'], ); })->middleware('auth'); What I measured for the two serving helpers on a PNG:
-
Storage::download($path, 'my picture.png')sentContent-Type: image/pngandContent-Disposition: attachment; filename="my picture.png". -
Storage::response($path)sentContent-Disposition: inlinewith the stored file name. - Neither sent
X-Content-Type-Optionsby default. Adding it through the headers argument worked (I confirmednosniffon the response). It tells browsers not to guess a different content type from the file's contents. - Passing
'attachment'as the fourth argument toresponse()switched the disposition to attachment.
A practical policy: inline only for images you re-encoded yourself; everything else as download(). If you must allow SVG, serve it as an attachment or from a separate cookieless domain, because inline SVG can run script in your origin.
For time-limited links, the Laravel docs say temporaryUrl works on the local and s3 drivers, and that older apps may need 'serve' => true on the local disk. My attempt on a hand-built disk failed with Route [storage.up] not defined, so I cannot vouch for the local setup beyond what the docs say. On S3, signed URLs are the standard approach.
Limits at every layer
The max rule only runs after PHP has accepted the upload. The limits that stop huge requests earlier are PHP's. On my CLI, upload_max_filesize was 2M and post_max_size 8M; check the values for your FPM or Apache SAPI with php -i | grep -E "upload_max_filesize|post_max_size" and keep them consistent with your validation. Your web server has its own body-size setting too (Nginx's is client_max_body_size); I did not test either server.
Common mistakes
- Using
extensions:as the only check. - Calling
move()orstoreAs()withgetClientOriginalName(). - Putting uploads under
public/because it is convenient. - Allowing SVG and serving it inline.
- Serving user files without any authorization because the name is hard to guess.
- Relying on
getClientMimeType(), which is whatever the client said.
Checklist
- Validate with content-based rules (
File::image(),File::types()) plus a size cap. - Store with
store()orputFile(), never the client name. - Use a private disk; expose files through an authorized route.
- Re-encode images where you can.
- Serve non-images as downloads and add
nosniff. - Set PHP and web server size limits to match your validation.
- Make sure no upload directory can execute code.
Related Dev Talk articles
Frequently asked questions
Is the mimes rule enough to secure uploads?
No. It checks that the content looks like an allowed type. A valid PNG with code appended passed my image check. You still need safe storage and serving.
Does Laravel rename uploaded files?
With store() and putFile(), yes: a random name with an extension taken from the detected content type. storeAs() and move() use the name you give them.
Should I allow SVG uploads?
Only if you need them. Laravel's image rule rejects SVG by default because of XSS risk. If you allow it, serve it as a download or from a separate domain.
Is it safe to store uploads in storage/app/public?
Files there become reachable by URL through the storage:link symlink. That is fine for content that is meant to be public and has been validated and re-encoded, and wrong for anything private.
Do I need antivirus scanning?
For files that other users download, such as documents, scanning with a tool like ClamAV is a reasonable extra layer. I did not test any scanner here.
update log
- 18 November 2026: first version.
- To recheck on each update: the list of types accepted by the
imagerule, the PHP-extension block list, and localtemporaryUrlbehavior.
Sources
- Laravel documentation: Validating files
- Laravel documentation: File storage
- laravel/framework: ValidatesAttributes (13.x)
- OWASP File Upload Cheat Sheet
Originally published on DEV Talk.