PHP Code Examples

Validate and Store File Uploads Safely in PHP

Validate upload errors, size, and MIME type, then store files outside the public web root using a generated filename.

Example

<?php
if (!isset($_FILES['document']) ||
    $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    exit('Upload failed.');
}

$file = $_FILES['document'];
$maxBytes = 5 * 1024 * 1024;

if ($file['size'] > $maxBytes) {
    exit('The file is too large.');
}

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

$allowed = [
    'application/pdf' => 'pdf',
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
];

if (!isset($allowed[$mime])) {
    exit('File type is not allowed.');
}

$filename = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
$destination = '/home/account/private-uploads/' . $filename;

if (!move_uploaded_file($file['tmp_name'], $destination)) {
    http_response_code(500);
    exit('Could not save the file.');
}

Important safeguards

The destination directory should not be executable or directly accessible from the web. Apply authentication and authorization, scan files where appropriate, and enforce upload limits at both PHP and web-server levels.

Share this page Help other developers discover this resource.