PHP Luminova: HTTP Request Upload File Object
HTTP File object encapsulates a file ready to be uploaded to a server. It offers customization to modify properties before finally uploading to the server.
The HTTP File
object represents a file ready to be uploaded to the server. With this class, you can customize files before sending them to the Uploader
or Storage
class for final upload. Optionally, you can change the filename or set a symlink
path to generate a symbolic link for files stored in the private storage directory.
Usage Example
Configuration:
Setting upload configurations for the file object
use Luminova\Http\Request;
// HTTP Request object
$request = new Request();
// Get file object from request object
$file = $request->getFile('image');
// Set various upload configurations
$file->setConfig([
'upload_path' => root('writeable/storages/uploads/'),
'max_size' => 10485760,
'min_size' => 1024,
'allowed_types' => 'png|jpg|gif|pdf',
'chunk_length' => 5242880,
'if_existed' => File::IF_EXIST_RETAIN,
'symlink' => '/public/assets/symlink',
]);
// Validate the file before proceeding with upload
if ($file->validation()->isError()) {
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,10MB
is the maximum size.min_size
: Sets the minimum allowable size for the file, such as1KB
in the example.allowed_types
: Restricts file types to specific extensions (png
,jpg
,gif
,pdf
).chunk_length
: Enables chunked file uploads, useful for large files (5MB
chunks in this case).if_existed
: Rule to 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/symlink
once the upload completes.
Handling Raw‑Binary (BLOB) Uploads
When a client‑side library sends your image as raw binary data (BLOB), you may see:
$file->extension
returns"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 your MIME‑to‑extension map
In your framework's file config, add any custom mappings for BLOB‑only uploads:
// /app/Config/Files.php
namespace App\Config;
use Luminova\Base\BaseConfig;
final class Files extends BaseConfig
{
/**
* Map additional MIME types to file extensions.
*
* @var array<string,string>
*/
protected static array $extensions = [
'image/png' => 'png',
'image/jpeg' => 'jpg',
// add other custom mappings here
];
}
Note: The base config already includes common types. Add only the extra ones you need.
2. Allow bin
as a temporary extension
Configure your uploader to accept .bin
files so raw uploads pass initial validation:
// Get file object from HTTP request
$file = $request->getFile('file');
$file->setConfig([
'allowed_types' => 'png|jpg|gif|bin'
// Other options...
]);
3. Post‑process and correct the extension
After the file is received, check for .bin
and use your detector to find the real MIME → extension:
use App\Config\Files;
// If the client sent a BLOB, extension is 'bin'
if ($file->getExtension() === 'bin') {
// 1) Detect actual MIME from temp file or raw data
$mime = $file->getMimeFromFile()
?? $file->getMime()
?? '';
// 2) Lookup the correct extension
$ext = Files::getExtension($mime);
// 3) Build new filename (preserving original basename)
$filename = rtrim($file->getName(), '.bin');
// Or create a new name entirely
// $filename = uniqid('file_');
// Update file name and extension
$file->setName("{$filename}.{$ext}", true);
}
4. Validate and upload
Finally, run your normal validation and upload logic:
use Luminova\Exceptions\InvalidException;
if (!$file->valid()) {
// Handle validation error
throw new InvalidException(sprintf(
'File validation failed: (%d) %s.',
$file->getError(),
$file->getMessage()
));
}
// Upload the corrected file
$status = Uploader::upload($file);
// Or upload using chunking
// $status = Uploader::chunk($file, null, $chunkIndex, $totalChunks);
// Output final upload message
echo $file->getMessage();
This ensures your server always saves images (and other files) with the correct extension and MIME metadata.
Class Definition
- Class namespace:
\Luminova\Http\File
- This class implements: \Luminova\Interface\LazyInterface
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 error no skip existing file. |
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
Represents a single uploaded file, with magic property access for its metadata.
Zero-based index when multiple files are uploaded.
protected int $index = 0;
The original filename (basename).
protected ?string $name = null;
The MIME type reported by the client (e.g., "image/jpeg").
protected ?string $type = null,
The file size in bytes.
protected int $size = 0,
The file extension (derived from name or MIME).
protected ?string $extension = null,
The temporary filesystem path, if available.
protected ?string $temp = null,
protected int $error = UPLOAD_ERR_NO_FILE,
Raw binary file contents (for blob/chunked uploads).
protected ?string $content = null,
True if uploaded as raw binary/blob or via chunking.
protected bool $is_blob = false
A validation or error message, if any.
protected ?string $message = 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 detect)
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->is_blob; // true|false
Methods
constructor
Constructs a File object.
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,
?string $content = null,
bool $is_blob = 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 | string|null | The file's content in string format, typically used as an alternative to using the temp when the file data is stored directly in memory (e.g., blobs). |
$is_blob | 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 ). |
Manual Instantiation 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,
is_blob: 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,
is_blob: true
);
getIndex
Gets the index of the file.
public getIndex(): int
Return Value:
int
- Return the index of the file.
getName
Gets the name of the file.
public getName(): ?string
Return Value:
string|null
- Return the name of the file.
getType
Gets the MIME type of the file.
public getType(): ?string
Return Value:
string|null
- Return the MIME type of the file.
getMime
Gets the MIME type of the file.
public getMime(): ?string
Return Value:
string|null
- Return the MIME type of the file.
Alias of
getType
.
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(): ?string
Return 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(): int
Return Value:
int
- Return the size of the file in bytes.
getExtension
Gets the file extension.
public getExtension(): ?string
Return Value:
string|null
- Return the file extension.
getTemp
Gets the temporary file path.
public getTemp(): ?string
Return Value:
string|null
- Return the temporary file path.
getError
Gets the error code of the file upload.
public getError(): int
Return Value:
int
- Return the error code of the file upload.
getMessage
Gets the validation message.
public getMessage(): ?string
Return Value:
string|null
- Return the validation message.
getConfig
Gets the file upload configurations.
The returned configuration object may contain the following properties:
- uploadPath
(string)
: The target path where uploaded files will be saved. - maxSize
(int)
: Maximum allowed file size in bytes. - minSize
(int)
: Minimum allowed file size in bytes. - allowedTypes
(array|string)
: List of permitted file extensions. - chunkLength
(int)
: 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)
: Path to create a symbolic link of the uploaded file. - base64Strict
(bool)
: Whether to enforce strict Base64 decoding for Base64-encoded uploads. - data
(mixed)
: Additional custom configuration information.
public getConfig(): ?\stdClass
Return Value:
\stdClass|null
- Returns the upload configuration object if set, or null if not configured.
setName
Sets the file name, with an option to replace its extension.
public setName(string $name, bool $replaceExtension = true): self
Parameters:
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 (default: true). |
Return Value:
self
- Returns the current file instance.
Throws:
- \Luminova\Exceptions\StorageException - Throws if the file name contains directory paths or, when
$replaceExtension
is enabled, lacks a valid file extension.
setConfig
Set file configurations for upload behavior.
public setConfig(array<string,string|int> $config): self
Parameters:
Parameter | Type | Description |
---|---|---|
$config | array<string,string|int> | An associative array of file configuration key and value. |
Return Value:
self
- Returns the current file instance.
Note: The configurations will be used in validating file before uploading to server.
Supported Configurations Keys
- upload_path -
(string)
The path where files will be uploaded. - max_size -
(int)
Maximum allowed file size in bytes. - min_size -
(int)
Minimum allowed file size in bytes. - allowed_types -
(string|string[])
Array of allowed file types or String separated by pipe symbol (e.g,png|jpg|gif
). - chunk_length -
(int)
Length of chunk in bytes (default:5242880
). - if_existed -
(string)
How to handle existing files (e.g,File::IF_EXIST_OVERWRITE
,File::IF_EXIST_*
) (default:File::IF_EXIST_OVERWRITE
). - symlink -
(string)
Specify a valid path to create a symlink after upload was completed (e.g/public/assets/
). - base64_strict - (bool) If true, base64_decode() will return false on invalid characters.
- data -
(mixed)
Additional custom configuration information.
setMessage
Sets the file's error or feedback message and status code.
Commonly used by the Luminova\Storages\Uploader
class to provide feedback on upload errors or processing issues.
public setMessage(string $message, int $code = UPLOAD_ERR_CANT_WRITE): self
Parameters:
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.
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(): bool
Return Value:
bool
- Returns true if the file is a BLOB, otherwise false.
isBase64Encoded
Determines if the uploaded content string is likely to be Base64-encoded.
public isBase64Encoded(): bool
Return 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
]);
isError
Checks if an error occurred during the file upload process.
public isError(): bool
Return Value:
bool
- Returns true if an error occurred; false otherwise.
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.
public free(): void
validate
Validates the uploaded file using configured rules such as file size, type, and upload status.
This method performs a full validation using valid()
and returns the current file instance.Use isError()
to determine if validation failed.
public validate(): self
Return Value:
self
- Returns the current File instance.
Example:
Validate a file:
if ($file->validate()->isError()) {
echo $file->getMessage(); // Error message
echo $file->getCode(); // Error code
}
valid
Executes file validation checks against the defined configuration rules.
This method performs a comprehensive check to verify if the file aligns with custom configuration constraints.
- Ensures upload completed without native PHP errors.
- Checks for non-zero size and temporary file/content availability.
- Validates against maximum/minimum file size constraints.
- Verifies the file extension against allowed types (if defined).
public valid(): bool
Return Value:
bool
- Returns true if the file passes all validations; otherwise false.
If a validation rule fails, an appropriate error code and message are set call
$file->getMessage()
for error or upload feedback message. And$file->getCode()
or$file->getError()
for upload error code.