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.