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.
protected int $size = 0;extension
The file extension (derived from name or MIME).
protected ?string $extension = null;temp
The temporary filesystem path, if available (e.g, temp_name).
protected ?string $temp = null;error
The upload error code (UPLOAD_ERR_* or File::UPLOAD_ERR_*).
protected int $error = UPLOAD_ERR_NO_FILE;content
Raw binary file contents (for blob/chunked uploads), or a stream.
protected StreamInterface|string|null $content = null;isBlob
True if uploaded as raw binary/blob or via chunking.
protected bool $isBlob = false;message
A validation or error message, if any.
protected ?string $message = null;mime
The MIME type detected from the temporary file or raw content. It stays null until getMimeFromFile is called.
protected ?string $mime = null;Accessing file instance properties via $file->propertyName:
echo $file->name; // e.g. "photo.jpg"
echo $file->type; // e.g. "image/jpeg"
echo $file->mime; // e.g. "image/png" (after getMimeFromFile())
echo $file->size; // e.g. 204800
echo $file->extension; // e.g. "jpg"
echo $file->temp; // e.g. "/tmp/phpYzdqkD"
echo $file->error; // e.g. UPLOAD_ERR_OK (0)
echo $file->message; // e.g. "File size exceeds limit."
echo $file->content; // e.g. binary data as string
echo $file->index; // e.g. 0
echo $file->isBlob; // true|falseReading a property that does not exist returns
null.
Methods
constructor
Constructs a File object for handling uploaded file data.
public __construct(
int $index = 0,
?string $name = null,
?string $type = null,
int $size = 0,
?string $extension = null,
?string $temp = null,
int $error = UPLOAD_ERR_NO_FILE,
\Psr\Http\Message\StreamInterface|string|null $content = null,
bool $isBlob = false
)Parameters:
| Parameter | Type | Description |
|---|---|---|
$index | int | The index of the file in the uploaded file array, typically representing the position in a multi-file upload scenario. |
$name | string|null | The original name of the uploaded file. This includes the file name and its extension (e.g., document.pdf). |
$type | string|null | The MIME type of the file (e.g., image/jpeg, application/pdf). This is used to identify the type of file uploaded for further processing or validation. |
$size | int | The size of the uploaded file in bytes. This value is essential for checking file size limits and ensuring compliance with upload restrictions. |
$extension | string|null | The file extension (e.g., jpg, png, pdf). This allows quick identification of the file type based on its extension and can be used for validation or categorization. |
$temp | string|null | The temporary file path where the uploaded file is stored on the server. This is the location from which the file can be moved or processed. |
$error | int | The error code associated with the file upload (e.g, UPLOAD_ERR_OK, UPLOAD_ERR_INI_SIZE). |
$content | StreamInterface|string|null | The file's content as a string or stream, typically used when the file data is stored directly in memory as an alternative to using the temp. |
$isBlob | bool | Indicates whether the uploaded file is handled as a binary large object (BLOB), which is commonly used for in-memory file storage (default: false). |
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If neither
tempnorcontentis provided.
Examples:
Create a new uploaded file object.
From a standard PHP upload:
$file = new File(
index: 0,
name: $_FILES['photo']['name'],
type: $_FILES['photo']['type'],
size: $_FILES['photo']['size'],
extension: pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION),
temp: $_FILES['photo']['tmp_name'],
error: $_FILES['photo']['error'],
content: null,
isBlob: false
);From raw binary (BLOB) data:
$binaryData = file_get_contents('php://input');
$file = new File(
index: 0,
name: 'upload.bin',
type: 'application/octet-stream',
size: strlen($binaryData),
extension: 'bin',
temp: null,
error: UPLOAD_ERR_OK,
content: $binaryData,
isBlob: true
);fromArray
Create a new uploaded file instance from an associative array.
Typically used with a normalized $_FILES entry or a custom file payload. Missing keys fall back to the constructor defaults.
public static fromArray(array $file): staticParameters:
| Parameter | Type | Description |
|---|---|---|
$file | array<string,mixed> | File data map. |
Supported keys:
| Key | Type | Default | Description |
|---|---|---|---|
index | int | 0 | File index in a multi-upload context. |
name | string|null | null | Original file name. |
type | string|null | null | MIME type of the file. |
size | int | 0 | File size in bytes. |
extension | string|null | null | File extension without the dot. |
temp | string|null | null | Temporary file path on the server. |
error | int | UPLOAD_ERR_NO_FILE | Upload error code. |
content | StreamInterface|string|null | null | Raw file content, used when the file was not uploaded through a temp file. |
isBlob | bool | false | Whether the file was created from binary data. |
Return Value:
static - Returns a new uploaded file instance.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - If neither
tempnorcontentis provided.
Example:
$file = File::fromArray([
'name' => 'photo.png',
'type' => 'image/png',
'size' => 204800,
'extension' => 'png',
'temp' => '/tmp/phpYzdqkD',
'error' => UPLOAD_ERR_OK,
]);setConfig
Configure file upload behavior and restrictions.
Applies upload rules such as size limits, allowed file types, storage location. The configurationcan be provided as a UploadedFileConfig instance or an associative array.
public setConfig(Luminova\Http\Config\UploadedFileConfig|array<string,mixed> $config): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$config | UploadedFileConfig|array<string,mixed> | Upload configuration options. |
Return Value:
self - Returns the current file instance.
Options
The configurations will be used in validating file before uploading to server. Array keys accept the snake case option names below, or the matching UploadedFileConfig property names (e.g., uploadPath). Unknown keys are ignored.
| Configuration | Type | Description |
|---|---|---|
upload_path | string | The path where files will be uploaded. The path is normalized with a trailing directory separator. |
max_size | int | Maximum allowed file size in bytes. |
min_size | int | Minimum allowed file size in bytes. |
allowed_types | string|string[] | A list or string of allowed file types, separated by a pipe symbol (e.g., png\|jpg\|gif). |
chunk_length | int | Write length of chunk in bytes. Default: null. |
if_existed | string | Defines how to handle existing files (e.g., File::IF_EXIST_RENAME, File::IF_EXIST_*). Default: File::IF_EXIST_OVERWRITE. |
symlink | string | A valid path to create a symlink after upload completion (e.g., /writeable/storages/, /public/assets/). |
data | mixed | Additional custom configuration data. |
base64_strict | bool | If true, base64_decode() will return false on invalid characters. Default: false. |
Throws:
- \Luminova\Exceptions\RuntimeException - If the upload path is empty, invalid or points to a file.
Examples:
Using array Configuration:
$file->setConfig([
'upload_path' => '/writeable/uploads',
'max_size' => 5_000_000,
'base64_strict' => true,
]);Using a Uploaded File Config object
use Luminova\Http\Config\UploadedFileConfig;
$config = UploadedFileConfig::fromArray([
'uploadPath' => '/writeable/uploads',
'maxSize' => 5_000_000,
'allowedTypes' => ['jpg', 'png'],
]);
$file->setConfig($config);use Luminova\Http\Config\UploadedFileConfig;
$config = new UploadedFileConfig(
uploadPath: '/writeable/uploads/',
maxSize: 5_000_000,
allowedTypes: ['jpg', 'png'],
base64StrictDecode: true
);
$file->setConfig($config);getConfig
Gets the file upload configurations.
If no configuration has been set, a new default UploadedFileConfig instance is created and returned.
The returned configuration object has the following properties:
- uploadPath
(string|null): The target path where uploaded files will be saved. - maxSize
(int|null): Maximum allowed file size in bytes. - minSize
(int|null): Minimum allowed file size in bytes. - allowedTypes
(array|string|null): List of permitted file extensions. - chunkLength
(int|null): Length of each file chunk in bytes (used for chunked uploads). - ifExisted
(string): Strategy to apply if the file already exists (e.g.,overwrite,retain,rename,skip). - symlink
(string|null): Path to create a symbolic link of the uploaded file. - base64StrictDecode
(bool): Whether to enforce strict Base64 decoding for Base64-encoded uploads. - data
(mixed|null): Additional custom configuration information.
public getConfig(): UploadedFileConfigReturn Value:
Luminova\Http\Config\UploadedFileConfig - Returns the instance of upload configuration.
Note: Property values may be null if not configured.
Example:
$config = $file->getConfig();
echo $config->uploadPath;
var_dump($config->data);validate
Validates the uploaded file using configured rules such as file size, type, and upload status.
Validation runs in this order and stops at the first failure:
- No temp file or content:
File::UPLOAD_ERR_NO_FILE_DATA. - Upload error reported by PHP: the original error code is kept, with a detailed message.
- File size is
0:File::UPLOAD_ERR_NO_SIZE. - Configured rules:
UPLOAD_ERR_INI_SIZE(abovemax_size),File::UPLOAD_ERR_MIN_SIZE(belowmin_size), andUPLOAD_ERR_EXTENSION(extension not inallowed_types).
When all checks pass, the error code is set to UPLOAD_ERR_OK. Use hasError() to determine if validation failed.
public validate(): selfReturn Value:
self - Returns the current File instance.
Example:
Validate a file:
if ($file->validate()->hasError()) {
echo $file->getMessage(); // Error message
echo $file->getError(); // Error code
}hasError
Checks if an error occurred during the file upload process.
If the file has not been validated yet (or the configuration changed since the last validation), validate() runs first. UPLOAD_ERR_PARTIAL is not treated as an error.
public hasError(): boolReturn Value:
bool - Returns true if an error occurred; false otherwise.
getError
Gets the error code of the file upload.
public getError(): intReturn Value:
int - Return the error code of the file upload.
getMessage
Gets the validation and upload message.
public getMessage(): ?stringReturn Value:
string|null - Return the validation error or upload message.
setName
Sets the file name, with an option to replace its extension.
public setName(string $name, bool $replaceExtension = true): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$name | string | The desired name of the file, without directory paths. |
$replaceExtension | bool | (optional) If true, updates the file extension based on the provided name, stored in lowercase (default: true). |
Return Value:
self - Returns the current file instance.
Throws:
- \Luminova\Exceptions\InvalidArgumentException - Throws if the file name contains a directory separator.
- \Luminova\Exceptions\RuntimeException - Throws if
$replaceExtensionis enabled and the file name lacks a valid file extension.
moveTo
Move the uploaded file to a new location.
Delegates to the Luminova\Http\Uploader class. For more advanced upload options, use the uploader directly.
public moveTo(string $targetPath): void Parameters:
| Parameter | Type | Description |
|---|---|---|
$targetPath | string | The destination path for the file. |
Throws:
- \Luminova\Exceptions\RuntimeException - Throws if the file was already moved or uploaded.
- \Luminova\Exceptions\InvalidArgumentException - Throws if the target path is empty.
setMessage
Sets the file's error or feedback message and status code.
Commonly used by the Luminova\Http\Uploader class to provide feedback on upload errors or processing issues. The file is marked as uploaded only when $code is UPLOAD_ERR_OK.
public setMessage(string $message, int $code = UPLOAD_ERR_CANT_WRITE): selfParameters:
| Parameter | Type | Description |
|---|---|---|
$message | string | The descriptive error or feedback message. |
$code | int | The status code (e.g., UPLOAD_ERR_* or File::UPLOAD_ERR_*) Defaults to UPLOAD_ERR_CANT_WRITE. |
Return Value:
self - Returns the current file instance.
getIndex
Gets the index of the file.
public getIndex(): intReturn Value:
int - Return the index of the file.
getName
Gets the name of the file.
public getName(): ?stringReturn Value:
string|null - Return the name of the file.
getType
Gets the MIME type of the file, as reported by the client.
public getType(): ?stringReturn Value:
string|null - Return the MIME type of the file.
getMime
Gets the MIME type of the file.
Alias: getType.
public getMime(): ?stringReturn Value:
string|null - Return the MIME type of the file.
getMimeFromFile
Detect and cache the MIME type from a temporary file or raw binary content.
This method will:
- If a temp file path (
$file->temp) is set, use it for detection. - Otherwise, fall back to raw binary data (
$file->content). - Cache the result in $file->mime and return it.
public getMimeFromFile(): ?stringReturn Value:
string|null - Return the detected MIME type (e.g., image/png), or null if no source is available or detection fails.
Useful for cases where the file is uploaded as (
BLOB), typically,the MIME type may default toapplication/octet-stream.
getSize
Gets the size of the file in bytes.
public getSize(): intReturn Value:
int - Return the size of the file in bytes.
getExtension
Gets the file extension.
public getExtension(): ?stringReturn Value:
string|null - Return the file extension.
getTemp
Gets the temporary file path.
public getTemp(): ?stringReturn Value:
string|null - Return the temporary file path.
getContent
Gets the file raw binary string content.
public getContent(): ?stringReturn Value:
string|null - Return the file content as a string, or null if there is no content.
getStream
Retrieve a stream representing the uploaded file.
The stream is read only. It is created from the existing stream content, the temporary file, or the raw content string, in that order.
public getStream(): StreamInterfaceReturn Value:
Psr\Http\Message\StreamInterface - Returns stream representation of the uploaded file.
Throws:
- \Luminova\Exceptions\RuntimeException - Throws if the file has already been uploaded, or the temporary file cannot be opened.
getImageInfo
Gets the image information of the file if it's an image.
The result is cached after the first call.
public getImageInfo(): ?Luminova\Components\Media\ImageInfoReturn Value:
Luminova\Components\Media\ImageInfo|null - Returns an ImageInfo object containing the dimensions and metadata of the image, or null if the file is not an image or the information cannot be determined.
getClientFilename
Retrieve the filename sent by the client.
Alias: getName.
public getClientFilename(): ?stringReturn Value:
string|null - Returns filename sent by the client or null if none was provided.
getClientMediaType
Retrieve the media type sent by the client.
Alias: getType.
public getClientMediaType(): ?stringReturn Value:
string|null - Returns media type sent by the client or null if none was provided.
isUploaded
Checks if file was uploaded successfully.
public isUploaded(): boolReturn Value:
bool - Returns true if file was uploaded, false otherwise.
isBlob
Determines if the file is uploaded as a BLOB (Binary Large Object).
This method checks whether the file was uploaded as a BLOB,typically used for large file uploads or when the file's content is handled directly in binary form.
public isBlob(): boolReturn Value:
bool - Returns true if the file is a BLOB, otherwise false.
isStream
Checks if file content is stream.
public isStream(): boolReturn Value:
bool - Returns true if file is stream, false otherwise.
isBinary
Determines if the uploaded content string is likely binary, based on the presence of non-printable characters.
public isBinary(): boolReturn Value:
bool - Returns true if the content is binary, false otherwise or when there is no content.
isBase64Encoded
Determines if the uploaded content string is likely to be Base64-encoded.
public isBase64Encoded(): boolReturn Value:
bool - Returns true if the content is likely to be Base64-encoded, false otherwise.
Example:
Setting base64 strict validation:
If true, base64_decode() will return false on invalid characters.
$file->setConfig([
'base64_strict' => true
]);free
Clears all file-related data, resets configuration, and removes the temporary file if it exists.
This method is typically called after processing or canceling an upload to ensure no temporary resources are left behind and the file object is safely reset. The error code is reset to UPLOAD_ERR_NO_FILE.
public free(): voidtoArray
Get array representation of uploaded file object.
This method creates an array from file-object properties into an associative array.
public toArray(): arrayReturn Value:
array<string, mixed> - Returns an array with the keys index, name, type, size, extension, temp, error, content, isBlob and isStream.
jsonSerialize
Returns the data used when the file object is encoded with json_encode(). The result is the same as toArray().
public jsonSerialize(): mixedReturn Value:
array<string, mixed> - Returns an array of file upload.
__toArray
Returns an array representation of the file object. The result is the same as toArray().
public __toArray(): arrayReturn Value:
array<string, mixed> - Returns an array of file upload.