BrowserUploadManager
in package
The BrowserUploadManager class is responsible for managing file uploads through the browser.
It handles operations related to uploading files to the server using HTTP forms.
Table of Contents
Properties
- $allowCancel : bool
- $allowChunked : bool
- $allowedExtensions : array<string|int, mixed>
- $allowedMimeTypes : array<string|int, mixed>
- $allowMultiple : bool
- $allowPauseResume : bool
- $chunkSize : int
- $finfo : finfo
- $generateRandomNames : bool
- $maxFiles : int
- $maxFileSize : int
- $maxTotalSize : int
- $overwriteExisting : bool
- $tempDir : string
- $uploadDir : string
Methods
- __construct() : void
- Create a new instance
- cancel() : array<string|int, mixed>
- Cancels an upload session and optionally deletes associated files.
- detectMime() : string
- Detects the MIME type of a file using finfo.
- finalizeChunk() : array<string|int, mixed>
- Finalizes a multi-chunk upload by merging all chunks into a single file.
- humanBytes() : string
- Converts bytes to a human-readable format.
- isImage() : bool
- Determines if a file is an image based on its MIME type.
- pause() : array<string|int, mixed>
- Pauses an ongoing upload session.
- resume() : array<string|int, mixed>
- Resumes a paused upload session.
- saveChunk() : array<string|int, mixed>
- Saves a chunk of data to temporary storage during multi-chunk upload processing.
- saveChunkFromRequest() : array<string|int, mixed>
- Handles chunk saving from an HTTP request by reading the chunk data from $_FILES.
- startChunkSession() : array<string|int, mixed>
- Initiates a new chunked upload session for a file.
- status() : array<string|int, mixed>
- Retrieves the status of an upload session by its ID.
- uploadFromField() : array<string|int, mixed>
- Uploads a single file from a specific POST field.
- uploadMultiple() : array<string|int, mixed>
- Uploads multiple files using standard file upload methods.
- uploadMultipleFromField() : array<string|int, mixed>
- Uploads multiple files from a specific POST field.
- uploadSingle() : array<string|int, mixed>
- Uploads a single file using standard file upload methods.
- buildFinalPath() : string
- Builds the final file path for a file, with optional random name generation.
- buildUniqueFinalPath() : string
- Builds a unique final file path by appending a random suffix to prevent filename conflicts.
- chunkDir() : string
- Generates the directory path for chunk files.
- chunkPath() : string
- Generates the file path for a specific chunk file.
- deleteChunkFiles() : void
- Deletes chunk files associated with a specific upload.
- ensureDirectory() : void
- The ensureDirectory method ensures that a specified directory exists.
- fail() : array<string|int, mixed>
- The fail method is used to return the failure of an operation.
- generateUploadId() : string
- Generates a unique upload ID.
- getProgressFromSession() : int
- Calculates the progress percentage from session data.
- loadSession() : array<string|int, mixed>|null
- Loads session data from a file.
- moveUploadedFile() : array<string|int, mixed>
- Processes the movement of an uploaded file to its final destination.
- normalizeFilesArray() : array<string|int, mixed>
- Normalizes the $_FILES array structure to ensure consistent formatting.
- ok() : array<string|int, mixed>
- The ok method is used to return the success of an operation.
- processStandardUpload() : array<string|int, mixed>
- Processes standard file uploads for multiple files.
- sanitizeFilename() : string
- Sanitizes a filename by removing/replacing invalid characters and normalizing whitespace.
- saveSession() : void
- Saves session data to a file.
- sessionPath() : string
- Generates the file path for a session file.
- uploadErrorMessage() : string
- The uploadErrorMessage method returns an error message based on the file upload error code.
- validateTitle() : string
- Validates and sanitizes a title string.
- validateUploadedFile() : array<string|int, mixed>
- Validates an uploaded file against multiple criteria.
Properties
$allowCancel
private
bool
$allowCancel
$allowChunked
private
bool
$allowChunked
$allowedExtensions
private
array<string|int, mixed>
$allowedExtensions
$allowedMimeTypes
private
array<string|int, mixed>
$allowedMimeTypes
$allowMultiple
private
bool
$allowMultiple
$allowPauseResume
private
bool
$allowPauseResume
$chunkSize
private
int
$chunkSize
$finfo
private
finfo
$finfo
$generateRandomNames
private
bool
$generateRandomNames
$maxFiles
private
int
$maxFiles
$maxFileSize
private
int
$maxFileSize
$maxTotalSize
private
int
$maxTotalSize
$overwriteExisting
private
bool
$overwriteExisting
$tempDir
private
string
$tempDir
$uploadDir
private
string
$uploadDir
Methods
__construct()
Create a new instance
public
__construct([array<string|int, mixed> $config = [] ]) : void
Parameters
- $config : array<string|int, mixed> = []
-
Configuration options
cancel()
Cancels an upload session and optionally deletes associated files.
public
cancel(string $uploadId[, bool $deleteFiles = true ]) : array<string|int, mixed>
This method handles the cancellation of an ongoing file upload by:
- Validating that cancellation is permitted
- Loading the existing session data
- Updating the session status to cancelled
- Optionally deleting temporary chunk files and manifest files
Parameters
- $uploadId : string
-
The unique identifier for the upload session
- $deleteFiles : bool = true
-
Whether to also delete associated chunk files
Return values
array<string|int, mixed> —An array containing either a success or error result
detectMime()
Detects the MIME type of a file using finfo.
public
detectMime(string $filePath) : string
This method uses PHP's finfo class to determine the MIME type of a file by examining its contents rather than relying solely on file extensions.
Parameters
- $filePath : string
-
The path to the file to analyze
Return values
string —The detected MIME type in lowercase, or 'application/octet-stream' if undetermined
finalizeChunk()
Finalizes a multi-chunk upload by merging all chunks into a single file.
public
finalizeChunk(string $uploadId) : array<string|int, mixed>
This method handles the finalization process of a chunked upload by:
- Validating the existence of the upload session
- Verifying that all chunks have been received
- Merging all chunk files into a single temporary file
- Performing final validation on the merged file
- Moving the merged file to its final destination
- Cleaning up temporary files and session data
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
array<string|int, mixed> —An array containing either a success or error result with finalization information
humanBytes()
Converts bytes to a human-readable format.
public
humanBytes(int $bytes) : string
This method converts a given number of bytes into a more readable format (B, KB, MB, GB, TB) by dividing by 1024 until the appropriate unit is found.
Parameters
- $bytes : int
-
The number of bytes to convert
Return values
string —A human-readable string representation of the byte value
isImage()
Determines if a file is an image based on its MIME type.
public
isImage(string $filePath) : bool
This method uses the detectMime function to check if a file has an image MIME type by examining if it starts with 'image/'.
Parameters
- $filePath : string
-
The path to the file to check
Return values
bool —True if the file is an image, false otherwise
pause()
Pauses an ongoing upload session.
public
pause(string $uploadId) : array<string|int, mixed>
This method handles pausing an active file upload by:
- Validating that pause/resume functionality is enabled
- Loading the existing session data
- Verifying that the current status is 'uploading'
- Updating the session status from 'uploading' to 'paused'
- Storing the updated session data for future resumption
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
array<string|int, mixed> —An array containing either a success or error result with pause confirmation
resume()
Resumes a paused upload session.
public
resume(string $uploadId) : array<string|int, mixed>
This method handles resuming an upload that was previously paused by:
- Validating that pause/resume functionality is enabled
- Loading the existing session data
- Verifying that the current status is 'paused'
- Updating the session status from 'paused' to 'uploading'
- Returning information about the resumed upload
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
array<string|int, mixed> —An array containing either a success or error result with resumed upload information
saveChunk()
Saves a chunk of data to temporary storage during multi-chunk upload processing.
public
saveChunk(string $uploadId, int $chunkIndex, string $chunkData) : array<string|int, mixed>
This method handles the saving of individual file chunks to disk, tracks which chunks have been received, and maintains progress tracking for the overall upload. It performs validation to ensure the chunk is valid and within the expected parameters.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
- $chunkIndex : int
-
The index/position of the chunk being saved
- $chunkData : string
-
The actual chunk data to save
Return values
array<string|int, mixed> —An array containing either a success or error result with progress information
saveChunkFromRequest()
Handles chunk saving from an HTTP request by reading the chunk data from $_FILES.
public
saveChunkFromRequest(string $uploadId) : array<string|int, mixed>
This method processes an incoming chunk upload request by:
- Extracting the chunk index from POST data
- Reading the actual chunk data from the uploaded file
- Validating that the data was read successfully
- Delegating the chunk saving to the main saveChunk method
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
array<string|int, mixed> —An array containing either a success or error result from the save operation
startChunkSession()
Initiates a new chunked upload session for a file.
public
startChunkSession(string $originalName, int $totalSize, int $totalChunks[, array<string|int, mixed> $meta = [] ]) : array<string|int, mixed>
This method creates and initializes a new upload session for a file that will be uploaded in chunks. It performs validation on the file and session parameters, generates a unique upload ID, and stores the session data for tracking the upload progress.
Parameters
- $originalName : string
-
The original name of the file being uploaded
- $totalSize : int
-
The total size of the file in bytes
- $totalChunks : int
-
The total number of chunks the file will be divided into
- $meta : array<string|int, mixed> = []
-
Additional metadata about the file (optional)
Return values
array<string|int, mixed> —An array containing either a success or error result with the new upload session information
status()
Retrieves the status of an upload session by its ID.
public
status(string $uploadId) : array<string|int, mixed>
This method fetches and returns the current status of an ongoing file upload, including progress information, chunk data, and metadata about the upload session.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
array<string|int, mixed> —An array containing the upload status and related information
uploadFromField()
Uploads a single file from a specific POST field.
public
uploadFromField([string $fieldName = 'file' ][, array<string|int, mixed> $meta = [] ]) : array<string|int, mixed>
This method handles the uploading of a single file by:
- Validating that the specified field exists in $_FILES
- Delegating to the uploadSingle method for processing
Parameters
- $fieldName : string = 'file'
-
The name of the POST field containing the file
- $meta : array<string|int, mixed> = []
-
Additional metadata about the file (optional)
Return values
array<string|int, mixed> —An array containing either a success or error result
uploadMultiple()
Uploads multiple files using standard file upload methods.
public
uploadMultiple(array<string|int, mixed> $files[, array<string|int, mixed> $meta = [] ]) : array<string|int, mixed>
This method handles the uploading of multiple files by:
- Normalizing the file input array structure
- Validating that the number of files doesn't exceed the allowed limit
- Processing all files through the standard upload pipeline
Parameters
- $files : array<string|int, mixed>
-
The file data from $_FILES
- $meta : array<string|int, mixed> = []
-
Additional metadata about the files (optional)
Return values
array<string|int, mixed> —An array containing either a success or error result
uploadMultipleFromField()
Uploads multiple files from a specific POST field.
public
uploadMultipleFromField([string $fieldName = 'files' ][, array<string|int, mixed> $meta = [] ]) : array<string|int, mixed>
This method handles the uploading of multiple files by:
- Validating that the specified field exists in $_FILES
- Delegating to the uploadMultiple method for processing
Parameters
- $fieldName : string = 'files'
-
The name of the POST field containing the files
- $meta : array<string|int, mixed> = []
-
Additional metadata about the files (optional)
Return values
array<string|int, mixed> —An array containing either a success or error result
uploadSingle()
Uploads a single file using standard file upload methods.
public
uploadSingle(array<string|int, mixed> $files[, array<string|int, mixed> $meta = [] ]) : array<string|int, mixed>
This method handles the uploading of a single file by:
- Normalizing the file input array structure
- Validating that exactly one file was submitted
- Processing the file through the standard upload pipeline
Parameters
- $files : array<string|int, mixed>
-
The file data from $_FILES
- $meta : array<string|int, mixed> = []
-
Additional metadata about the file (optional)
Return values
array<string|int, mixed> —An array containing either a success or error result
buildFinalPath()
Builds the final file path for a file, with optional random name generation.
private
buildFinalPath(string $originalName) : string
This method takes an original filename, sanitizes it, and constructs the final destination path in the upload directory. If random name generation is enabled, it appends a random 16-character hexadecimal string to the filename to prevent conflicts.
Parameters
- $originalName : string
-
The original filename provided by the user
Return values
string —The complete file path where the file should be stored
buildUniqueFinalPath()
Builds a unique final file path by appending a random suffix to prevent filename conflicts.
private
buildUniqueFinalPath(string $originalName) : string
This method takes an original filename, sanitizes it, and appends a random 12-character hexadecimal string to create a unique filename. It handles both files with and without extensions by preserving the original extension when one exists.
Parameters
- $originalName : string
-
The original filename provided by the user
Return values
string —A unique file path that helps prevent filename conflicts
chunkDir()
Generates the directory path for chunk files.
private
chunkDir(string $uploadId) : string
This method creates a directory path for storing chunk files by combining the temporary directory path with the upload ID.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
string —The complete directory path for the chunks
chunkPath()
Generates the file path for a specific chunk file.
private
chunkPath(string $uploadId, int $chunkIndex) : string
This method creates a unique file path for a chunk file by combining the chunks directory path with the chunk index and .part extension.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
- $chunkIndex : int
-
The index/position of the chunk
Return values
string —The complete file path for the chunk
deleteChunkFiles()
Deletes chunk files associated with a specific upload.
private
deleteChunkFiles(string $uploadId) : void
This method removes all temporary chunk files and the directory for a given upload ID. It first checks if the directory exists, then iterates through all .part files in the directory and unlinks them one by one. Finally, it removes the directory itself.
Parameters
- $uploadId : string
-
The unique identifier for the upload
ensureDirectory()
The ensureDirectory method ensures that a specified directory exists.
private
ensureDirectory(string $dir) : void
If the directory doesn't exist, it attempts to create it with the appropriate permissions. If the directory creation fails, it throws a RuntimeException.
Parameters
- $dir : string
-
The directory path to check or create
Tags
fail()
The fail method is used to return the failure of an operation.
private
fail(string $message[, array<string|int, mixed> $extra = [] ]) : array<string|int, mixed>
Parameters
- $message : string
-
Error message
- $extra : array<string|int, mixed> = []
-
Additional error information
Return values
array<string|int, mixed> —Array containing the failure information
generateUploadId()
Generates a unique upload ID.
private
generateUploadId() : string
This method creates a cryptographically secure random identifier using binary-to-hexadecimal conversion of random bytes for use as a unique identifier for upload sessions.
Return values
string —A hexadecimal encoded random string
getProgressFromSession()
Calculates the progress percentage from session data.
private
getProgressFromSession(array<string|int, mixed> $session) : int
This method determines the progress of a multi-part file upload or operation by comparing the number of received chunks with the total number of expected chunks.
Parameters
- $session : array<string|int, mixed>
-
Session data containing chunk information
Return values
int —The progress percentage (0-100), or 0 if no valid data
loadSession()
Loads session data from a file.
private
loadSession(string $uploadId) : array<string|int, mixed>|null
This method retrieves stored session data (such as upload progress information) from a JSON file in the temporary directory based on the upload ID. It reads the file, decodes the JSON data, and returns the parsed array.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
array<string|int, mixed>|null —The session data if successful, null otherwise
moveUploadedFile()
Processes the movement of an uploaded file to its final destination.
private
moveUploadedFile(array<string|int, mixed> $file, array<string|int, mixed> $meta) : array<string|int, mixed>
This method handles the complete process of moving an uploaded file from the temporary location to the final destination, including:
- Validating the upload status and file integrity
- Sanitizing the filename and extracting metadata
- Performing size and type validations
- Generating appropriate file paths
- Moving the file with proper error handling
Parameters
- $file : array<string|int, mixed>
-
The uploaded file data from $_FILES
- $meta : array<string|int, mixed>
-
Additional metadata for the file
Return values
array<string|int, mixed> —An array containing either a success or error result with file information
normalizeFilesArray()
Normalizes the $_FILES array structure to ensure consistent formatting.
private
normalizeFilesArray(array<string|int, mixed> $files) : array<string|int, mixed>
This method standardizes the structure of the $_FILES superglobal array, which can have different formats depending on whether multiple files are uploaded under the same name. It ensures that all file information is presented in a consistent array format regardless of how many files were uploaded.
Parameters
- $files : array<string|int, mixed>
-
The raw $_FILES array or subset of it
Return values
array<string|int, mixed> —An array with normalized file information, where each element represents a single file
ok()
The ok method is used to return the success of an operation.
private
ok(array<string|int, mixed> $data) : array<string|int, mixed>
Parameters
- $data : array<string|int, mixed>
-
Data to return on success
Return values
array<string|int, mixed> —Array containing the success information
processStandardUpload()
Processes standard file uploads for multiple files.
private
processStandardUpload(array<string|int, mixed> $files, array<string|int, mixed> $meta, bool $multiple) : array<string|int, mixed>
This method handles the complete upload process for one or more files, including:
- Validating each uploaded file against size and type restrictions
- Checking total size limits across all files
- Moving valid files to their final destination
- Returning structured results with file information
Parameters
- $files : array<string|int, mixed>
-
The array of files from $_FILES
- $meta : array<string|int, mixed>
-
Additional metadata for the files
- $multiple : bool
-
Flag indicating if multiple files are being processed
Return values
array<string|int, mixed> —An array containing either a success or error result with all processed files
sanitizeFilename()
Sanitizes a filename by removing/replacing invalid characters and normalizing whitespace.
private
sanitizeFilename(string $name) : string
This method performs multiple sanitization steps on a filename:
- Extracts the basename (removes any directory paths)
- Trims whitespace from both ends
- Removes or replaces invalid characters like null bytes, carriage returns, etc.
- Replaces non-alphanumeric characters (except spaces, dots, and hyphens) with underscores
- Normalizes multiple consecutive whitespace characters into a single underscore
- Removes or replaces multiple consecutive underscores with a single underscore
- Trims dots, hyphens, and spaces from both ends
Parameters
- $name : string
-
The original filename to sanitize
Return values
string —The sanitized filename
saveSession()
Saves session data to a file.
private
saveSession(string $uploadId, array<string|int, mixed> $session) : void
This method stores the session data (such as upload progress information) to a JSON file in the temporary directory. The session data includes information about uploaded chunks, total chunks, and other relevant metadata.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
- $session : array<string|int, mixed>
-
The session data to save
sessionPath()
Generates the file path for a session file.
private
sessionPath(string $uploadId) : string
This method creates a complete file path for a session data file by combining the temporary directory path with the upload ID and JSON extension.
Parameters
- $uploadId : string
-
The unique identifier for the upload session
Return values
string —The complete file path for the session file
uploadErrorMessage()
The uploadErrorMessage method returns an error message based on the file upload error code.
private
uploadErrorMessage(int $code) : string
Parameters
- $code : int
-
The file upload error code
Return values
string —The appropriate error message to display
validateTitle()
Validates and sanitizes a title string.
private
validateTitle(string $title) : string
This method processes a title by trimming whitespace, replacing multiple consecutive whitespace characters with a single space, and performing validation checks. It ensures the title meets basic quality requirements for length and non-emptiness.
Parameters
- $title : string
-
The title to validate and sanitize
Tags
Return values
string —The sanitized title (trimmed and with normalized whitespace)
validateUploadedFile()
Validates an uploaded file against multiple criteria.
private
validateUploadedFile(array<string|int, mixed> $file[, array<string|int, mixed> $meta = [] ]) : array<string|int, mixed>
This method performs comprehensive validation on an uploaded file, checking for:
- Upload errors
- File integrity (temporary file validation)
- File name validity
- File size constraints
- Allowed file extensions Allowed MIME types File title validation
Parameters
- $file : array<string|int, mixed>
-
The uploaded file data from $_FILES
- $meta : array<string|int, mixed> = []
-
Additional metadata for the file
Return values
array<string|int, mixed> —An array containing either a success or error result