Development
How to Upload Files Securely in PHP

Upload files securely in PHP by checking the upload error and size, identifying an allowed content type, generating the destination name on the server, and storing the result outside the web document root. Authentication and authorization must happen before accepting the file.
The browser's filename, extension, and content-type header are untrusted input. None should decide where a file is written or whether it may execute.
Define the upload boundary first
This handler accepts only JPEG uploads up to 2 MiB. It belongs at public/upload.php, with a pre-created writable var/uploads/ directory beside public/. It assumes the application's authenticated session already contains an integer user_id and a random csrf_token created by the application. Do not expose it before integrating that session contract.
The HTML form must use method="post", enctype="multipart/form-data", a file input named photo, and the session token in a hidden field named csrf_token. Escape that token with htmlspecialchars() when rendering it.
Upload files securely in PHP
<?php
declare(strict_types=1);
session_start();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Allow: POST');
http_response_code(405);
exit;
}
if (!is_int($_SESSION['user_id'] ?? null)) {
http_response_code(401);
exit;
}
$token = $_POST['csrf_token'] ?? null;
$expected = $_SESSION['csrf_token'] ?? null;
if (!is_string($token) || !is_string($expected)
|| $expected === '' || !hash_equals($expected, $token)) {
http_response_code(403);
exit;
}
$file = $_FILES['photo'] ?? null;
if (!is_array($file)
|| !is_int($file['error'] ?? null)
|| !is_string($file['tmp_name'] ?? null)
|| $file['error'] !== UPLOAD_ERR_OK
|| !is_uploaded_file($file['tmp_name'])) {
http_response_code(400);
exit('A successful photo upload is required.');
}
$size = filesize($file['tmp_name']);
if ($size === false || $size < 1 || $size > 2 * 1024 * 1024) {
http_response_code(413);
exit('The photo must be between 1 byte and 2 MiB.');
}
if ((new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']) !== 'image/jpeg') {
http_response_code(415);
exit('Only JPEG photos are accepted.');
}
$directory = dirname(__DIR__) . '/var/uploads';
$name = bin2hex(random_bytes(24)) . '.jpg';
if (!move_uploaded_file($file['tmp_name'], $directory . '/' . $name)) {
http_response_code(500);
exit('The upload could not be stored.');
}
http_response_code(201);
header('Content-Type: application/json');
echo json_encode(['file_id' => $name], JSON_THROW_ON_ERROR);
The response identifier is not an authorization mechanism. Persist the owner and file identifier together in your application's storage, and enforce ownership again when serving or deleting the file. The example demonstrates the receiving boundary, not a complete attachment database.
PHP's upload documentation, move_uploaded_file reference, and Fileinfo documentation describe the underlying operations.
Keep upload storage non-executable and private
Set the actual web document root to public/. A directory named var is not private if the server also exposes the project root. The application account should have only the filesystem permissions it needs.
Do not return the filesystem path. A download endpoint should resolve an application-owned identifier, check permission, and send a deliberate content type and disposition. The paid download protection guide shows why a direct file URL must be tested separately from a page containing its link.
MIME identification is one layer, not proof that a file is harmless. For images, bounded decoding and re-encoding can create a controlled derivative. Reject unreasonable dimensions before allocating image memory, and consider malware scanning where the threat model requires it.
Align the web server and PHP limits
Review upload_max_filesize, post_max_size, temporary storage, request body limits, timeouts, and disk quotas. When the request body exceeds a configured limit, the application may receive empty form data instead of a normal per-file upload error.
Add per-user quotas and abuse controls before accepting repeated uploads. Use a cleanup policy for files that are stored successfully but never attached to an application record.
Verify the rejection paths
Test a valid small JPEG, an empty file, an oversized JPEG, a renamed text file, nested upload fields, a missing token, and an unauthenticated session. Confirm that every rejected request leaves no stored file. These are environment acceptance steps, not a claim that a complete authenticated deployment has already been exercised.
Is checking the extension enough?
No. The client chooses the filename. Use an explicit type policy, independent content checks, controlled storage, and authorization throughout the lifecycle.
For help reviewing that full lifecycle, scope a PHP upload security review.