Overview
File uploads combine untrusted content, filesystem operations and potentially expensive processing. A secure upload workflow validates the request, inspects the file, assigns a server-generated name and stores it outside executable public paths whenever possible.
Enforce limits early
Set appropriate upload_max_filesize and post_max_size values, then enforce application-level limits for file size, count and allowed formats. Check the upload error code and ensure the file was uploaded through PHP's HTTP upload mechanism.
Do not trust the filename or browser MIME type
Generate a random storage name. Determine the media type on the server using Fileinfo and validate the file signature or parse it with a suitable library. An extension allowlist is useful but insufficient by itself. Reject unexpected formats and malformed content.
Store safely
Prefer a private directory outside the document root. If public downloads are required, serve files through a controlled endpoint that checks authorization and sets safe content headers. Never allow uploaded PHP, HTML or script files to execute. Apply web-server rules as an additional layer, not as the only defense.
Example checks
<?php
if (!isset($_FILES['upload']) || $_FILES['upload']['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Upload failed.');
}
$file = $_FILES['upload'];
if ($file['size'] > 5 * 1024 * 1024) {
throw new RuntimeException('File is too large.');
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png'];
if (!isset($allowed[$mime])) {
throw new RuntimeException('Unsupported file type.');
}
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
// Move to a private, non-executable storage directory.
This is a starting point, not a complete image validation pipeline. Decode and re-encode images when appropriate, scan files when risk warrants it, and protect the upload form with CSRF controls.
Official references
Validate the upload at multiple layers
Check the upload error code, size limit and server-detected MIME type. Do not trust the browser-provided filename or Content-Type. Use an allowlist of required formats and, where appropriate, inspect file signatures with finfo.
<?php
$file = $_FILES['document'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Upload failed.');
}
if ($file['size'] > 5 * 1024 * 1024) {
throw new RuntimeException('File is too large.');
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']);
$allowed = ['application/pdf' => 'pdf'];
if (!isset($allowed[$mime]) || !is_uploaded_file($file['tmp_name'])) {
throw new RuntimeException('Unsupported file type.');
}
$name = bin2hex(random_bytes(16)) . '.' . $allowed[$mime];
$destination = '/private/uploads/' . $name;
if (!move_uploaded_file($file['tmp_name'], $destination)) {
throw new RuntimeException('Could not store upload.');
}
The destination must be a private directory outside the public document root. The example is intentionally restrictive; adapt the MIME allowlist to the formats the application truly needs.
Prevent execution and resource abuse
Never use the supplied filename as a storage path. Apply per-user quotas, request-size limits, rate limits and safe image/PDF processing limits. If files must be downloaded, serve them through an authorized controller with a safe content disposition rather than exposing the storage directory.
Malware scanning and lifecycle
For higher-risk workflows, integrate malware scanning or content disarm and reconstruction where appropriate. Quarantine files until checks finish. Define retention, deletion and backup policies so abandoned uploads do not accumulate indefinitely.
Test hostile cases
Test double extensions, MIME mismatches, oversized files, empty files, malformed documents, path traversal strings and concurrent uploads. Ensure uploaded content cannot be executed by the web server.