PHP Luminova: Http File Uploader
The Uploader class handles local file uploads, supports chunked uploads for large files, and integrates with the File object to provide flexible configuration and detailed upload feedback.
The HTTP File Uploader class is built into the Luminova Framework as a lightweight alternative to the Luminova\Storage\Storage class. It is designed for handling local file uploads efficiently, offering methods like:
uploadfor standard file uploads,movefor moving a validated HTTP upload from its temporary location,chunkfor large files using client-side chunking,writefor saving content directly from a string, stream or file object,progressfor reading the progress of an active upload.
This class works well with the Http Uploaded File Object (Luminova\Http\File), enabling customizable upload handling and clear, detailed feedback for each upload process.
Usages
Using Upload with File Object
Upload a file to the server. You can optionally pass the upload_path in the second parameter or set it in the file configuration using the setConfig method.
use Luminova\Http\Uploader;
use function Luminova\Funcs\root;
$file = $request->getFile('file');
if ($file->hasError()) {
echo $file->getMessage();
return;
}
$upload = Uploader::upload(
$file,
root('writeable/storages/images/'),
0,
$destination
);
if($upload){
echo "Upload was successful: {$destination}";
}
// Get message from file object
echo $file->getMessage();The uploader throws a
StorageExceptionwhen the file has a validation error, so check$file->hasError()before uploading.After an upload, the file object is freed: its temporary file is deleted and its configuration is cleared.
Using Write with String Content
To write content to a file.
use Luminova\Http\Uploader;
use function Luminova\Funcs\root;
$upload = Uploader::write(
root('writeable/storages/files/', 'hello.txt'),
'Hello world'
);
if($upload){
echo 'Upload was successful';
}Using Chunk with File Object
This example demonstrates how you can upload a large file using the chunk method and browser-side chunking like Plupload or similar.
// /app/Controller/Http/UploadController.php
namespace App\Controllers\Http;
use Luminova\Http\Uploader;
use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use function Luminova\Funcs\root;
#[Prefix(pattern: '/upload/(:root)')]
class UploadController extends Controller
{
#[Route('/upload/file', methods: ['POST'])]
public function upload(): int
{
$file = $this->request->getFile('file');
if (!$file) {
return $this->response(400)
->json(['message' => 'No file uploaded or invalid file.']);
}
// Set upload configurations
$file->setConfig([
'upload_path' => root('writeable/storages/images/'),
'chunk_length' => 5242880 /* The length of each chunk in bytes (default is 5MB) */
]);
if ($file->hasError()) {
return $this->response(400)
->json(['message' => 'File validation failed: ' . $file->getMessage()]);
}
// Get the current chunk index and total chunks from the request
$chunk = (int) $this->request->getPost('chunk', 0);
$chunks = max(1, (int) $this->request->getPost('chunks', 1));
$status = Uploader::chunk($file, chunkIndex: $chunk, totalChunks: $chunks);
if ($status === true) {
// File was uploaded
return $this->response(201)
->json(['message' => 'File uploaded successfully.']);
}
if (is_int($status)) {
// Chunk was written, more chunks are expected
return $this->response(206)->json([
'message' => 'File partially uploaded.',
'remaining' => $status
]);
}
// Failed to upload file
return $this->response(500)->json([
'message' => 'File upload failed.',
'error' => $file->getMessage()
]);
}
}Each request to the backend must contain the total number of chunks and the zero-based index of the chunk being uploaded.Always compare the result with
trueusing a strict check, because the method also returns an integer when chunks remain.
Handling Existing Files
When a file with the same name already exists in the destination, the behavior is controlled by the if_existed file configuration.
| Value | Constant | Behavior |
|---|---|---|
overwrite | File::IF_EXIST_OVERWRITE | Deletes the existing file and saves the new one. |
rename | File::IF_EXIST_RENAME | Renames the existing file with a backup_ prefix and saves the new one. |
retain | File::IF_EXIST_RETAIN | Keeps the existing file and saves the new one with a new_ prefix. |
skip | File::IF_EXIST_SKIP | Skips the upload. The method returns true, $destination stays null, and the file error code is set to File::UPLOAD_ERR_SKIPPED. |
Any unrecognized value behaves like skip, which is also the behavior when if_existed is not set.
The
retainrule generates a new random name on every call, so it is not suitable forchunk, where each request must resolve to the same destination.
Handle Upload Progress
Use Uploader::progress() to retrieve the progress of an active file upload. You can expose it through a route or controller and poll the endpoint with JavaScript.
Example Route Definition
Define a route to return the upload progress as JSON.
// /routes/upload.php
use Luminova\Http\Uploader;
use function Luminova\Funcs\response;
Router::get('/upload/progress/(:string)', function (string $id): int {
return response()->json(Uploader::progress($id));
});Example Controller
Alternatively, handle upload progress in a controller.
// /app/Controllers/Http/UploadController.php
namespace App\Controllers\Http;
use Luminova\Http\Uploader;
use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
#[Prefix(pattern: '/upload/(:root)')]
class UploadController extends Controller
{
/**
* Retrieve the progress of an active file upload.
*
* @param string $id The upload progress identifier.
*
* @return int Status code.
*/
#[Route('/progress/(:string)', methods: ['GET'])]
public function progress(string $id): int
{
return $this->response()->json(Uploader::progress($id));
}
}Upload with Progress Tracking
Add a hidden input to your upload form to identify the upload being tracked. Its name must match PHP's session.upload_progress.name setting, which defaults to PHP_SESSION_UPLOAD_PROGRESS. The value identifies the upload.
<form action="/upload" method="POST" enctype="multipart/form-data">
<input
type="hidden"
name="PHP_SESSION_UPLOAD_PROGRESS"
value="upload_123"
>
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>Check Upload Progress with JavaScript
Poll the progress endpoint while the file is uploading.
async function checkUploadProgress(id) {
const response = await fetch(
`/upload/progress/${encodeURIComponent(id)}`
);
if (!response.ok) {
throw new Error('Failed to retrieve upload progress.');
}
return response.json();
}
checkUploadProgress('upload_123')
.then(progress => console.log(progress))
.catch(console.error);Example response:
{
"enabled": true,
"session": "started",
"active": true,
"received": 5242880,
"total": 10485760,
"percent": 50.0
}The received and total fields represent bytes received and total upload size. The percent field indicates the upload completion percentage, while active indicates whether PHP reports the upload as still in progress.
Important:
- The upload and progress requests must use the same session cookie and compatible session configuration.
- PHP must receive the upload body while it is being transmitted for progress updates to be available. Web server request buffering can delay these updates.
- Progress data may disappear after the upload completes because PHP cleans it up by default.
- Protect the progress endpoint so users can only access uploads they are authorized to track.
Class Definition
- Class namespace:
Luminova\Http\Uploader - This class is marked as final and can't be subclassed
Methods
upload
Uploads a file to the server by transferring data from the file object's temporary source or string content to the destination. Large files are written in chunks to a .part file and renamed once complete.
Files that have a temporary file and are 5 MB or smaller are handed to move instead, so the temporary file must be a real HTTP upload. Content based files (for example blobs or base64 strings) are written directly, and base64 content is decoded before writing.
public static upload(
File $file,
?string $path = null,
int $delay = 0,
?string &$destination = null
): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$file | Luminova\Http\File | The instance of file object being uploaded. |
$path | string|null | Optional upload path, if not set in the file configuration. |
$delay | int | Optional delay between chunk writes to limit resource usage (default: 0). |
&$destination | string|null | Output variable holding the final upload path, or null if the upload fails or is skipped. |
Return Value:
bool Returns true if the upload is successful or skipped by the skip rule, false otherwise.
Throws:
- \Luminova\Exceptions\StorageException Throws if the upload path is not configured or is not a directory path, the file has a validation error, or the upload directory could not be created.
chunk
Uploads a file in chunks to a specified destination.
This method supports large file uploads by splitting the file into smaller, manageable parts. The chunk splitting is typically done from the client side, e.g. JavaScript, using libraries like Plupload or similar to handle chunking before sending data.
Each chunk is appended to a .part file next to the destination, which is renamed to the final name after the last chunk is written. The first chunk (index 0) starts a new .part file. When $totalChunks is 1 and the file is 5 MB or smaller, the file is moved directly using move.
public static chunk(
File $file,
?string $path = null,
int $chunkIndex = 0,
int $totalChunks = 1,
float|int $delay = 0,
?string &$destination = null
): bool|intParameters:
| Parameter | Type | Description |
|---|---|---|
$file | Luminova\Http\File | The file instance being uploaded. |
$path | string|null | Optional directory path for the upload. If not provided, it falls back to the file configuration. |
$chunkIndex | int | The zero-based index of the current chunk (default: 0). |
$totalChunks | int | The total number of chunks for the file, minimum 1 (default: 1). |
$delay | float|int | Optional delay in seconds between chunk writes to manage resource usage (default: 0). When 0 and the configured chunk length is above 10 MB, a delay of 0.01 seconds is applied. |
&$destination | string|null | Output variable holding the final destination path when the upload completes, or null otherwise. |
Return Value:
bool|int Returns true if the upload is complete and false on failure. If more chunks are expected, returns the number of remaining chunks and sets the file error code to UPLOAD_ERR_PARTIAL.
The method returns false when $chunkIndex is negative, $totalChunks is less than 1, or $chunkIndex is not lower than $totalChunks. Validation rules such as max_size apply to the file received in each request, which is a single chunk.
Throws:
- \Luminova\Exceptions\StorageException Throws if the upload path is not configured or is not a directory path, the file has a validation error, or the upload directory could not be created.
move
Moves an uploaded file from a temporary location to a permanent destination on the server.
This method uses the traditional PHP move_uploaded_file, so the file must be a valid HTTP upload. It returns false for content only files, which have no temporary file.
public static move(File $file, ?string $path = null, ?string &$destination = null): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$file | Luminova\Http\File | The file object being moved. |
$path | string|null | Optional upload path, if not set in the file configuration. |
&$destination | string|null | Output variable holding the final destination path, or null if the move fails or is skipped. |
Return Value:
bool Returns true if the move is successful or skipped by the skip rule, false otherwise.
Throws:
- \Luminova\Exceptions\StorageException Throws if the upload path is not configured or is not a directory path, the file has a validation error, or the upload directory could not be created.
write
Writes content to a file at the specified path. The parent directory is created when it does not exist.
public static write(string $filename, File|resource|string $contents, string $mode = 'w'): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$filename | string | The full file path where the content should be written (e.g, path/to/text.txt). |
$contents | Luminova\Http\File|resource|string | The content to write, either a string, a stream resource or a file object that carries content. |
$mode | string | The write mode. Use a or ab to append, any other value overwrites the file (default: w). |
Behavior:
- A stream resource must be backed by a file or URI. Pipes, sockets and
php://streams are rejected, and the resource is closed after writing. - When a
Fileobject is given, its string content is written (base64 content is decoded first). The file is saved inside the directory of$filenameusing the file object's own name, and the file configuration rules, such asif_existedandsymlink, apply. A file object without content returnsfalse.
Return Value:
bool Returns true if the file is written successfully, false otherwise.
Throws:
- \Luminova\Exceptions\StorageException Throws only when a
Fileobject is passed and its upload path is invalid or the file has a validation error.
progress
Retrieves the progress of an active file upload from the PHP session. The $id must match the value submitted through the session.upload_progress.name form field.
public static progress(
string $id,
SessionConfig|array|null $config = null,
?string $sessionId = null
): arrayParameters:
| Parameter | Type | Description |
|---|---|---|
$id | string | The upload progress identifier. Only letters, numbers, underscores and hyphens are accepted, up to 128 characters. |
$config | App\Config\Session|array|null | Optional session configuration. It must match the configuration used by the upload request. When null, a default configuration with strict mode enabled is used. |
$sessionId | string|null | Optional PHP session identifier. |
Return Value:
array Returns the tracking status with the following keys:
| Key | Type | Description |
|---|---|---|
enabled | bool | Whether upload progress tracking is enabled in PHP. |
session | string | Session state: none (not started), started or failed. |
active | bool | Whether PHP reports the upload as still in progress. |
received | int | Bytes received so far. |
total | int | Total upload size in bytes. |
percent | float | Completion percentage, rounded to two decimals. |
When tracking is disabled, the identifier is invalid, or no progress data exists for the identifier, the defaults are returned (
false,0and0.0). A session is started only when one is not already active.