FileManager

Introduction

The FileManager class in JiFramework provides a comprehensive set of methods for handling file operations such as uploading, resizing images, extracting file information, directory management, and more. It simplifies common file-related tasks, ensuring security and efficiency within your application.

Key Features:

  • File Uploading: Securely upload files with validation and optional resizing for images.
  • File Information Extraction: Retrieve detailed information from uploaded files, including MIME types and hashes.
  • Directory Management: Ensure directories exist and are writable, creating them if necessary.
  • Image Processing: Resize and save images while preserving quality and aspect ratio.
  • File Deletion and Listing: Delete files and list files within directories, with support for recursion.
  • File Downloading: Serve files for download to the browser with proper headers.

Configurable Options:

Some methods in the FileManager class rely on configuration constants defined in the Config class. These include:

  • Config::UPLOAD_DIRECTORY: Default directory for file uploads.
  • Config::MAX_FILE_SIZE: Maximum allowed file size for uploads.
  • Config::ALLOWED_IMAGE_TYPES: Allowed MIME types for image uploads.
  • Config::IMAGE_MAX_DIMENSION: Maximum dimension for resizing images.

Usage:

// Option 1: Initialize the DateTimeHelper through the App
use JIFramework\Core\App\App;

$app = new App();
$fileManager = $app->fileManager;

// Option 2: Directly instantiate the FileManager
use JIFramework\Core\Utilities\FileManager;

$fileManager = new FileManager();

Explanation:

  • Option 1: Initializes the App class and retrieves the FileManager instance through it, using the framework's main entry point.
  • Option 2: Directly creates a FileManager instance.

extractFileInfo()

Method: extractFileInfo(array $file): object

Description: Extracts detailed information from a single uploaded file, including MIME types, file hash, and modification time.

Parameters:

  • $file (array): The file array from $_FILES.

Returns: An object containing enhanced file information:

  • name (string): Original file name.
  • extension (string): File extension in lowercase.
  • size (int): File size in bytes.
  • tmpName (string): Temporary file path.
  • typeProvided (string): MIME type provided by $_FILES.
  • actualType (string): Actual MIME type determined using finfo.
  • modificationTime (int): Last modification time of the file.
  • hash (string): SHA-256 hash of the file content.

Throws:

  • Exception: If the file is not a valid uploaded file.

Usage:

try {
    $fileInfo = $fileManager->extractFileInfo($_FILES['uploadedFile']);
    /*
    Sample $fileInfo:

    object(stdClass)#1 (8) {
      ["name"]=> string(12) "example.jpg"
      ["extension"]=> string(3) "jpg"
      ["size"]=> int(102400)
      ["tmpName"]=> string(14) "/tmp/phpYzdqkD"
      ["typeProvided"]=> string(10) "image/jpeg"
      ["actualType"]=> string(10) "image/jpeg"
      ["modificationTime"]=> int(1697389800)
      ["hash"]=> string(64) "e3b0c44298fc1c149afbf4c8996fb924... (truncated)"
    }
    */
    echo "File Name: " . $fileInfo->name . "\n";
    echo "File Size: " . $fileInfo->size . " bytes\n";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Explanation:

  • Checks if the file was uploaded via HTTP POST for security.
  • Uses finfo to determine the actual MIME type.
  • Generates a SHA-256 hash of the file content.
  • Retrieves the last modification time of the file.
  • Returns an object with detailed file information.

extractMultipleFileInfo()

Method: extractMultipleFileInfo(array $files): array

Description: Extracts detailed information from multiple uploaded files.

Parameters:

  • $files (array): The files array from $_FILES, typically when uploading multiple files.

Returns: An array of objects, each containing enhanced file information (same as extractFileInfo).

Throws:

  • Exception: If any file is not a valid uploaded file.

Usage:

try {
    $fileInfos = $fileManager->extractMultipleFileInfo($_FILES['uploadedFiles']);
    /*
    Sample $fileInfos:

    array(2) {
      [0]=>
        object(stdClass)#1 (8) { ... }
      [1]=>
        object(stdClass)#2 (8) { ... }
    }
    */
    foreach ($fileInfos as $fileInfo) {
        echo "File Name: " . $fileInfo->name . "\n";
        echo "File Size: " . $fileInfo->size . " bytes\n";
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Explanation:

  • Iterates over each file in the $files array.
  • Validates each file and extracts detailed information.
  • Returns an array of file information objects.

ensureDirectoryExists()

Method: ensureDirectoryExists(string $path): string

Description: Ensures that a directory exists and is writable, creating it if necessary.

Parameters:

  • $path (string): The directory path to check or create.

Returns: The directory path (string).

Throws:

  • Exception: If the directory cannot be created or is not writable.

Usage:

try {
    $directory = $fileManager->ensureDirectoryExists('/path/to/directory');
    /*
    Sample $directory:

    "/path/to/directory"
    */
    echo "Directory ensured at: " . $directory;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Explanation:

  • Checks if the directory exists; if not, attempts to create it with permissions 0755.
  • Ensures the directory is writable; if not, attempts to set the permissions.
  • Returns the directory path upon success.

resizeAndSaveImage()

Method: resizeAndSaveImage(string $photoPath, int $maxDim = null, string $savePath = null): bool

Description: Resizes an image to a specified maximum dimension while maintaining aspect ratio and saves it to a specified path.

Parameters:

  • $photoPath (string): The path to the original image file.
  • $maxDim (int, optional): The maximum dimension (width or height) in pixels. Defaults to Config::IMAGE_MAX_DIMENSION.
  • $savePath (string, optional): The path to save the resized image. Defaults to overwriting the original file.

Returns: true on success, false on failure.

Usage:

try {
    $result = $fileManager->resizeAndSaveImage('/path/to/image.jpg', 800, '/path/to/resized_image.jpg');
    /*
    Sample $result:

    true
    */
    echo $result ? "Image resized successfully." : "Failed to resize image.";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Explanation:

  • Determines new dimensions while maintaining aspect ratio.
  • Supports JPEG, PNG, and GIF image types.
  • Preserves transparency for PNG and GIF images.
  • Saves the resized image to the specified path.
  • Returns true on successful resize and save.

uploadFile()

Method: uploadFile(array $file, string $destination = null, int $maxSize = null, array $allowedTypes = null): array

Description: Uploads a file to a specified directory with validation and returns the result.

Parameters:

  • $file (array): The file array from $_FILES.
  • $destination (string, optional): The directory to save the uploaded file. Defaults to Config::UPLOAD_DIRECTORY.
  • $maxSize (int, optional): The maximum allowed file size in bytes. Defaults to Config::MAX_FILE_SIZE.
  • $allowedTypes (array, optional): An array of allowed MIME types. Defaults to Config::ALLOWED_IMAGE_TYPES.

Returns: An array containing:

  • success (bool): Indicates if the upload was successful.
  • data (object): The file information object (on success).
  • error (string): Error message (on failure).

Usage:

$result = $fileManager->uploadFile($_FILES['uploadedFile']);
/*
Sample $result on success:

array(2) {
  ["success"]=> bool(true)
  ["data"]=>
    object(stdClass)#1 (10) { ... }
}

Sample $result on failure:

array(2) {
  ["success"]=> bool(false)
  ["error"]=> string(31) "File size exceeds the maximum allowed limit."
}
*/

if ($result['success']) {
    $fileInfo = $result['data'];
    echo "File uploaded successfully. Saved as: " . $fileInfo->uniqueName;
} else {
    echo "Error: " . $result['error'];
}

Explanation:

  • Ensures the destination directory exists.
  • Extracts file information and validates size and MIME type.
  • Generates a unique file name to prevent conflicts.
  • Moves the uploaded file to the destination directory.
  • Returns an array indicating success or failure with relevant data.

deleteFile()

Method: deleteFile(string $filePath): bool

Description: Deletes a file from the filesystem.

Parameters:

  • $filePath (string): The path to the file to delete.

Returns: true on success, false on failure.

Usage:

$result = $fileManager->deleteFile('/path/to/file.txt');
/*
Sample $result:

true
*/

echo $result ? "File deleted successfully." : "Failed to delete file.";

Explanation:

  • Checks if the file exists.
  • Attempts to delete the file using unlink().
  • Returns true if the file was deleted, false otherwise.

listFiles()

Method: listFiles(string $directory, bool $recursive = false): array

Description: Retrieves a list of files within a directory, optionally including subdirectories.

Parameters:

  • $directory (string): The directory path to list files from.
  • $recursive (bool, optional): Whether to include files in subdirectories. Default is false.

Returns: An array of file paths.

Usage:

$files = $fileManager->listFiles('/path/to/directory', true);
/*
Sample $files:

array(3) {
  [0]=> string(20) "/path/to/directory/file1.txt"
  [1]=> string(26) "/path/to/directory/subdir/file2.jpg"
  [2]=> string(26) "/path/to/directory/subdir/file3.png"
}
*/

foreach ($files as $file) {
    echo "Found file: " . $file . "\n";
}

Explanation:

  • Uses DirectoryIterator or RecursiveDirectoryIterator based on the $recursive parameter.
  • Collects file paths of all regular files (excluding directories).
  • Returns an array of file paths.

downloadFile()

Method: downloadFile(string $filePath, string $filename = null): void

Description: Initiates a file download to the browser, setting appropriate headers.

Parameters:

  • $filePath (string): The path to the file to download.
  • $filename (string, optional): The name to give the downloaded file. Defaults to the basename of $filePath.

Returns: void

Throws:

  • Exception: If the file does not exist or cannot be read.

Usage:

try {
    $fileManager->downloadFile('/path/to/file.txt', 'downloaded_file.txt');
    // Note: The script will exit after initiating the download.
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Explanation:

  • Checks if the file exists and is readable.
  • Determines the MIME type and file size.
  • Sets HTTP headers to prompt the browser to download the file.
  • Reads the file and outputs it to the browser.
  • Calls exit() after sending the file to prevent further script execution.