File Upload Handling

7 questions found

How does PHP handle file uploads submitted through an HTML form, and what information does the $_FILES superglobal provide?

Beginner
When a user submits a form containing a file input with the proper multipart encoding, PHP automatically stores information about the uploaded file in the $_FILES superglobal, including the file's original name, its temporary server side location, its size, and its MIME type, along with an error code indicating whether the upload succeeded, giving your script everything it needs to validate and then move the uploaded file to a permanent location.
<form method="post" enctype="multipart/form-data">
  <input type="file" name="document">
</form>

$fileName = $_FILES['document']['name'];
$tmpPath = $_FILES['document']['tmp_name'];
Real-world example A document upload feature reads the temporary file path and original file name from the $_FILES superglobal immediately after a form submission, using that information to decide where and under what name to permanently store the uploaded file.

Common follow-ups: Why does the form need the enctype multipart form data attribute for file uploads to work?;What does each possible value of the upload error code mean?

Form Handling & Validation;Security

How do you move an uploaded file from its temporary location to a permanent storage location using move_uploaded_file?

Beginner
The move_uploaded_file function safely moves a file that was uploaded through an HTTP POST request from its temporary server location to a permanent destination you specify, and it specifically verifies that the file was genuinely uploaded through PHP's upload mechanism rather than being an arbitrary file path, providing an important security check compared to using a generic file move function for this specific purpose.
$destination = 'uploads/' . basename($_FILES['document']['name']);
if (move_uploaded_file($_FILES['document']['tmp_name'], $destination)) {
    echo 'Upload successful';
}
Real-world example A file upload handler moves a successfully validated upload from its temporary location into a permanent uploads folder using move_uploaded_file, taking advantage of its built in verification that the file genuinely came from a legitimate upload.

Common follow-ups: Why is move_uploaded_file preferred over a generic rename or copy function for this purpose?;What happens if move_uploaded_file fails, such as due to a permissions issue on the destination folder?

Security;File Handling & File System Functions

How should you validate an uploaded file's type and size before accepting it, and why is checking only the file extension considered insufficient for security?

Intermediate
You should validate an uploaded file's actual content type using functions that inspect the file's real content, such as checking its MIME type through PHP's fileinfo extension, rather than trusting only the file extension or the client provided MIME type in $_FILES, since both of those can be easily manipulated by a malicious user, and you should also enforce a maximum file size both in your PHP configuration and in your application code to prevent excessively large uploads.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['document']['tmp_name']);
if (!in_array($mimeType, ['image/jpeg', 'image/png'])) {
    throw new InvalidArgumentException('Invalid file type');
}
Real-world example An image upload feature verifies the actual content of an uploaded file using the fileinfo extension rather than trusting the file extension alone, blocking a malicious user who attempted to disguise an executable script as an image simply by renaming its extension.

Common follow-ups: What is the difference between the client provided MIME type and the actual detected MIME type?;How do you configure the maximum upload file size at the PHP configuration level?

Security;File Handling & File System Functions

How do you handle multiple file uploads submitted from a single form field, and what does the resulting $_FILES array structure look like?

Intermediate
When a file input is configured to accept multiple files using an array style field name, the $_FILES superglobal organizes the data slightly differently, storing each attribute, such as name or tmp_name, as its own array containing one entry per uploaded file, meaning you typically need to loop through these parallel arrays using a shared numeric index to process each individual uploaded file correctly.
<input type="file" name="documents[]" multiple>

foreach ($_FILES['documents']['name'] as $index => $name) {
    $tmpPath = $_FILES['documents']['tmp_name'][$index];
    move_uploaded_file($tmpPath, 'uploads/' . $name);
}
Real-world example A photo gallery upload feature lets users select and upload several images at once, looping through the resulting parallel arrays in $_FILES to process and store each individual uploaded photo correctly.

Common follow-ups: How does this array structure change if you use a modern framework's file upload handling instead of raw $_FILES?;What happens if a user selects zero files for a multiple file upload input?

Form Handling & Validation;Basics & Types

How should uploaded file names be sanitized and randomized to avoid security risks and naming conflicts when storing files on the server?

Intermediate
Uploaded file names, since they originate from user input, should never be trusted or used directly as the final storage file name without sanitization, since a malicious file name could contain path traversal sequences or unexpected characters, and a common best practice is to generate a completely new, randomized file name, such as a unique identifier combined with the original file extension, both eliminating naming conflicts between different users' uploads and removing any risk associated with the original, untrusted file name.
$extension = pathinfo($_FILES['document']['name'], PATHINFO_EXTENSION);
$safeFileName = bin2hex(random_bytes(16)) . '.' . $extension;
move_uploaded_file($_FILES['document']['tmp_name'], 'uploads/' . $safeFileName);
Real-world example A document management system generates a completely random file name for every uploaded file, storing the original user provided file name separately in a database record for display purposes, while the actual file on disk uses a safe, randomly generated name.

Common follow-ups: Why is it risky to use the original uploaded file name directly as the storage file name?;How do you keep track of the original file name if the storage file name is randomized?

Security;PDO & Databases

What security risks arise from allowing file uploads into a publicly accessible directory, and how do you prevent uploaded files from being executed as scripts?

Advanced
If uploaded files are stored within a publicly web accessible directory, and an attacker successfully uploads a malicious script disguised as an allowed file type, that directory's web server configuration might allow the malicious file to actually be executed if requested directly, which is why best practice includes storing uploads outside the public web root when possible, configuring the web server to explicitly disable script execution within upload directories, and validating file content thoroughly rather than relying on extension checks alone.
# Nginx configuration to prevent script execution in uploads directory
location /uploads/ {
    location ~ \.php$ { deny all; }
}
Real-world example A company discovers during a security audit that its uploads directory would have allowed an uploaded PHP file to be executed if requested directly, and immediately reconfigures its web server to explicitly deny script execution within that specific directory as a critical defense in depth measure.

Common follow-ups: What is the difference between storing uploads inside versus outside the public web root?;How does a content delivery network or dedicated object storage service like S3 help mitigate this specific risk entirely?

Security;Deployment & Hosting for PHP Applications

How should a large scale application design its file upload architecture to handle high volumes of uploads reliably, including virus scanning and offloading storage to a dedicated service?

Advanced
A robust large scale file upload architecture typically offloads actual file storage to a dedicated object storage service rather than the application server's own local disk, which does not scale well across multiple servers, integrates automated virus and malware scanning on every uploaded file before it becomes accessible to other users, processes uploads asynchronously through a background job queue for tasks like generating image thumbnails or extracting document metadata, and enforces strict validation and rate limiting to prevent abuse of the upload feature.
// Simplified flow
// 1. Validate and temporarily store upload
// 2. Queue background job for virus scan and processing
// 3. Move to permanent object storage only after passing all checks
Real-world example A large document sharing platform processes every uploaded file through an automated virus scanning service and generates preview thumbnails as background jobs, only making a file available for others to download once it has fully passed every validation and security check.

Common follow-ups: What tools are commonly used for automated virus scanning of uploaded files?;How does offloading storage to a dedicated object storage service improve scalability compared to local disk storage?

PHP with Docker;Design Patterns in PHP