CodShot
PHP Public

Basic Upload Validation

Validate upload error, size, and MIME type before accepting a file.

#php #upload #validation #security
PHP
<?php

$file = $_FILES['avatar'] ?? null;

if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
    throw new RuntimeException('Upload failed.');
}

if ($file['size'] > 2 * 1024 * 1024) {
    throw new RuntimeException('The file is too large.');
}

$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);

$allowed = ['image/jpeg', 'image/png', 'image/webp'];

if (!in_array($mime, $allowed, true)) {
    throw new RuntimeException('Invalid file type.');
}

Notes

This is a minimal pattern. Production uploads should also check permissions and storage quota.

Snippet actions

CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support