Loading...

File Uploads

In PHP development, uploaded files are sent via HTML forms and managed using the superglobal $_FILES array. This array contains detailed information about each uploaded file, including its original name, type, size, and temporary storage location. Mastering file uploads requires a solid understanding of PHP concepts such as syntax, data structures (arrays and objects), algorithms for handling file processing, and object-oriented programming (OOP) principles to build robust, scalable, and secure systems.
This tutorial will teach readers how to implement secure and efficient file upload functionality, including validating file types, restricting file sizes, handling errors, and managing directories. Learners will also understand how to integrate uploads into broader software architectures while following PHP best practices, ensuring system stability, security, and maintainability. By the end of this lesson, developers will be equipped to implement real-world file upload solutions that meet advanced PHP project requirements.

Basic Example

php
PHP Code
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['userfile']) && $_FILES['userfile']['error'] === UPLOAD_ERR_OK) {
$uploadDir = __DIR__ . '/uploads/';
$uploadedFile = $uploadDir . basename($_FILES['userfile']['name']);

if ($_FILES['userfile']['size'] > 5 * 1024 * 1024) {
echo "File is too large.";
exit;
}

$fileType = mime_content_type($_FILES['userfile']['tmp_name']);
if (!in_array($fileType, ['image/jpeg', 'image/png', 'image/gif'])) {
echo "Unsupported file type.";
exit;
}

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadedFile)) {
echo "File uploaded successfully.";
} else {
echo "File upload failed.";
}
} else {
echo "No file selected.";
}
}
?>

<form method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="userfile">
<input type="submit" value="Upload File">
</form>

In the basic example above, the script first checks that the request method is POST, which is essential for handling file uploads securely. The $_FILES array is used to determine whether a file was uploaded and to check for errors using $_FILES['userfile']['error']. The script then defines an upload directory and uses basename to prevent directory traversal attacks.
This example demonstrates a fundamental file upload workflow, combining syntax, arrays, and conditional logic. It follows PHP best practices for security and maintainability and serves as a foundation for more advanced implementations, including directory management, exception handling, and OOP integration.

Practical Example

php
PHP Code
<?php
class FileUploader {
private string $uploadDir;
private array $allowedTypes;
private int $maxSize;

public function __construct(string $dir, array $types, int $sizeMB) {
$this->uploadDir = $dir;
$this->allowedTypes = $types;
$this->maxSize = $sizeMB * 1024 * 1024;
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
}
}

public function upload(array $file): bool {
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Error during file upload.');
}

if ($file['size'] > $this->maxSize) {
throw new RuntimeException('File is too large.');
}

$fileType = mime_content_type($file['tmp_name']);
if (!in_array($fileType, $this->allowedTypes)) {
throw new RuntimeException('Unsupported file type.');
}

$destination = $this->uploadDir . basename($file['name']);
if (!move_uploaded_file($file['tmp_name'], $destination)) {
throw new RuntimeException('Failed to move uploaded file.');
}
return true;
}
}

try {
$uploader = new FileUploader(__DIR__ . '/uploads/', ['image/jpeg','image/png'], 5);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$uploader->upload($_FILES['userfile']);
echo "File uploaded successfully using object-oriented approach.";
}
} catch (RuntimeException $e) {
echo "Error: " . $e->getMessage();
}
?>

<form method="post" enctype="multipart/form-data">
Select a file: <input type="file" name="userfile">
<input type="submit" value="Upload File">
</form>

In the practical example, file upload functionality is encapsulated within a FileUploader class, leveraging object-oriented programming (OOP) for better organization and reusability. The constructor initializes upload directory, allowed file types, and maximum file size, creating the directory if it does not exist.

Performance optimizations involve configuring upload_max_filesize and post_max_size appropriately, creating directories as needed, and setting proper permissions. Security considerations include preventing execution of uploaded scripts, verifying MIME types and extensions, and restricting upload paths to prevent unauthorized access. Following these practices ensures that file uploads are safe, efficient, and maintainable in real-world PHP projects.

📊 Reference Table

PHP Element/Concept Description Usage Example
$_FILES Superglobal array containing uploaded file information $_FILES['userfile']['name']
move_uploaded_file Safely moves temporary file to target directory move_uploaded_file($_FILES['userfile']['tmp_name'], $destination)
mime_content_type Retrieve file MIME type $type = mime_content_type($_FILES['userfile']['tmp_name']);
UPLOAD_ERR_OK Constant indicating successful upload if ($_FILES['userfile']['error'] === UPLOAD_ERR_OK)
mkdir Create a directory if it does not exist mkdir($uploadDir, 0755, true);
RuntimeException Exception handling for upload errors throw new RuntimeException('Upload failed');

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

3
Questions
🎯
70%
To Pass
♾️
Time
🔄
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top