PHP

Validate Uploaded File

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A defense-in-depth check for $_FILES uploads: confirms the upload completed, the size is within bounds, the MIME type matches an allow-list (by libmagic, not by extension), and the file landed where PHP expected.
PHP
Raw
<?php
function validateUpload(array $file, array $allowedMime, int $maxBytes = 5_000_000): array {
    if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
        return [false, 'Upload failed (error code ' . ($file['error'] ?? -1) . ')'];
    }
    if (!is_uploaded_file($file['tmp_name'])) {
        return [false, 'Not an HTTP upload'];
    }
    if ($file['size'] <= 0 || $file['size'] > $maxBytes) {
        return [false, 'File size out of bounds'];
    }
    $mime = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
    if (!in_array($mime, $allowedMime, true)) {
        return [false, "Disallowed MIME type: $mime"];
    }
    return [true, null];
}

[$ok, $err] = validateUpload($_FILES['avatar'] ?? [], ['image/jpeg', 'image/png'], 2_000_000);
if (!$ok) { http_response_code(400); exit($err); }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.