PHP Luminova: HTTP Uploaded File Object
Represents an incoming uploaded file, with tools to validate, configure, and manage file properties before saving it to the server.
The Luminova File Uploaded Object represents an incoming file prepared for upload to the server. It provides detailed information about the file and allows customization before passing it to the local uploader handler (Luminova\Http\Uploader) or the remote storage handler (Luminova\Storage\Storage) for final processing.
This class supports files uploaded either as raw binary blobs or as native PHP temporary files. It allows you to define structured validation rules such as:
- Supported file formats
- Maximum and minimum allowed sizes
- Behavior when a file with the same name already exists
- Optional filename changes
- Creation of symbolic links (symlinks) for files stored in private directories
The uploaded file object class is optimized for easy integration with the local uploader handler (Luminova\Http\Uploader), which efficiently handles both small and large file uploads. When passed to the uploader, detailed upload progress messages are provided, and all configured rules are automatically applied.
Examples
Accessing File Object
When a file is uploaded, the Luminova HTTP Request object (Luminova\Http\Request) automatically includes all details about the current request, including any uploaded files.
Accessing Files in Controller Classes:
// app/Controllers/Http/UploadController.php
namespace App\Controllers\Http;
use Generator;
use Luminova\Base\Controller;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
#[Prefix('/upload/(:root)')]
class UploadController extends Controller
{
#[Route('/upload/file', methods: ['POST'])]
public function doUpload(): int
{
$files = $this->request->getFile('image');
// Handle multiple files
if ($files instanceof Generator) {
foreach ($files as $file) {
// Process each uploaded file
}
return STATUS_SUCCESS;
}
// Handle a single uploaded file
return STATUS_SUCCESS;
}
}Notes:
- Use
$this->request->getFile('field_name')to access uploaded files.- If multiple files are uploaded using the same field name, a
Generatoris returned.- For single file uploads, a single
Fileobject is returned.
Upload Configuration:
Setting upload configurations for the file object
use Luminova\Http\File;
use Luminova\Http\Request;
use Luminova\Exceptions\InvalidException;
// HTTP Request object
$request = new Request();
// Get file object from HTTP request object
$file = $request->getFile('image');
// Set various upload configurations
$file->setConfig([
'upload_path' => root('writeable/storages/images/'),
'max_size' => 10485760,
'min_size' => 1024,
'allowed_types' => 'png|jpg|gif|pdf',
'chunk_length' => 5242880,
'if_existed' => File::IF_EXIST_RETAIN,
'symlink' => '/public/assets/images',
]);
// Validate the file before proceeding with upload
if ($file->validate()->hasError()) {
throw new InvalidException(sprintf(
'File validation failed: (%d) %s.',
$file->getError(),
$file->getMessage()
));
}
echo 'File is valid for upload';Explanation:
upload_path: Specifies thewriteable/storages/uploads/as the path where the file will be saved on the server.max_size: Defines the maximum allowable file size. In this example,10MBis the maximum size.min_size: Sets the minimum allowable size for the file, such as1KBin the example.allowed_types: Restricts file types to specific extensions (png,jpg,gif,pdf).chunk_length: Enables chunked file uploads, useful for large files (5MBchunks in this case).if_existed: Rule that determines how to handle existing files (e.g,File::IF_EXIST_RETAIN) retains old versions of files.symlink: Creates a symlink in the specified path/public/assets/symlinkonce the upload completes.
Handling Binary Uploads
When a client-side library sends your image as raw binary data (BLOB), you may see:
$file->extensionreturns"bin"instead of"png".$file->type(or$file->getMime()) returns"application/octet-stream"instead of"image/png".
Uploading it without proper handling will result in your file being stored as file-name.bin.Below is the recommended workflow to detect and correct the real extension and MIME type before saving the file.
1. Extend Custom MIME and Extensions
Luminova ships with a built-in MIME database that covers common file types.You only need to extend it when handling custom or vendor-specific uploads.
Custom MIME definitions can be registered during application class or inside an upload controller (for example, in an onCreate() method).
use Luminova\Utility\Mime;
// Load a custom MIME database from a JSON file
Mime::database('/writable/custom/mime.json');
// Load from a plain text MIME list
Mime::database('/writable/custom/mime.txt');
// Load from a PHP file that returns an array
Mime::database('/writable/custom/mime.php');
// Load a compiled MIME magic database (.mgc) for binary detection
Mime::database('/writable/custom/mime.mgc');
// Register a MIME type manually
Mime::register('custom', 'application/custom-type');Note:
The Mime module already includes standard file types.Only register additional mappings when the default list does not cover your use case.
2. Temporarily Allow BIN Extension
When handling raw or BLOB-based uploads, files may initially be detected as generic binary data.To avoid early rejection, allow the .bin extension during the first validation phase.
// Get the uploaded file from the HTTP request
$file = $request->getFile('file');
$file->setConfig([
'allowed_types' => 'png|jpg|gif|bin',
// other upload options...
]);Why this matters:The
.binextension acts as a safe placeholder until the file’s real MIME type is detected and mapped.Once detection completes, Luminova resolves the correct extension based on the MIME database.
3. Post-Process and Correct the Extension
Once the file is received, raw binary files (with .bin) need proper extension assignment.Use Luminova's MIME detector to determine the correct MIME type and map it to the appropriate extension.
use Luminova\Utility\Mime;
// If the uploaded file has a '.bin' extension
if ($file->getExtension() === 'bin') {
// 1) Detect the actual MIME type from the temp file or raw data
$mime = $file->getMimeFromFile()
?? $file->getMime()
?? '';
// 2) Find the correct extension for the detected MIME
$ext = Mime::findExtension($mime);
// 3) Build a new filename (preserve original name without the extension)
$filename = pathinfo($file->getName(), PATHINFO_FILENAME);
// Optionally, generate a completely new name
// $filename = uniqid('file_');
// 4) Update the file name and extension
$file->setName("{$filename}.{$ext}", true);
}This step ensures uploaded binary blobs are properly recognized and stored with the correct extension, preventing issues with downstream processing or client downloads.
4. Validate and Upload
After correcting the file extension, run your standard validation and upload workflow.
use Luminova\Http\Uploader;
use Luminova\Exceptions\InvalidException;
// Validate the file
if ($file->validate()->hasError()) {
throw new InvalidException(sprintf(
'File validation failed: (%d) %s.',
$file->getError(),
$file->getMessage()
));
}
// Perform the upload
$status = Uploader::upload($file);
// Uploading using moveTo
// $file->moveTo('target')
// Using chunked uploads
// $status = Uploader::chunk($file, null, $chunkIndex, $totalChunks);
// Output final status or message
echo $file->getMessage();Notes:
- Validation ensures size, type, and other restrictions are enforced.
- Luminova's
Uploaderclass handles both standard and chunked uploads.$file->getMessage()provides human-readable feedback for logging or display.- Call
validate()again after changing the name or extension, sincehasError()only validates once until the configuration changes.
Class Definition
- Class namespace:
Luminova\Http\File - This class implements:
Psr\Http\Message\UploadedFileInterface, \Luminova\Interface\LazyObjectInterface, \Luminova\Interface\Arrayable
Constants
Custom Upload Error Codes
These constant define additional custom error code.
| Constant | Type | Value | Description |
|---|---|---|---|
UPLOAD_ERR_NO_SIZE | int | 9 | Custom upload error: file has no size. |
UPLOAD_ERR_MIN_SIZE | int | 10 | Custom upload error: file is below the minimum allowed size. |
UPLOAD_ERR_NO_FILE_DATA | int | 11 | Upload error no temp file or data. |
UPLOAD_ERR_SKIPPED | int | 12 | Upload skipped because the file already exists. |
Existing File handling Rules
These constant are available rules for handling existing files.
| Constant | Type | Value | Description |
|---|---|---|---|
IF_EXIST_RETAIN | string | retain | Keep the existing file and save the new one with a random prefix. |
IF_EXIST_OVERWRITE | string | overwrite | Overwrite the existing file if it already exists. |
IF_EXIST_RENAME | string | rename | Rename the existing file with a random prefix and save the new one. |
IF_EXIST_SKIP | string | skip | Skip the upload if the file already exists. |
Properties
The file object exposes its metadata through protected properties, readable from outside the class through magic property access ($file->propertyName).
index
Zero-based index when multiple files are uploaded.
protected int $index = 0;name
The original filename (basename).
protected ?string $name = null;type
The MIME type reported by the client (e.g., "image/jpeg").
protected ?string $type = null;size
The file size in bytes.