PHP code example of thingmabobby / file-upload-service

1. Go to this page and download the library: Download thingmabobby/file-upload-service library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

thingmabobby / file-upload-service example snippets


use FileUploadService\FileUploadService;

// Simple usage - FilesystemSaver auto-configured from uploadDestination
$service = new FileUploadService(['image', 'pdf']);

try {
    $result = $service->save(
        input: $_FILES['files'],
        uploadDestination: __DIR__ . '/uploads',  // Absolute path - basePath derived automatically!
        filenames: ['photo.jpg', 'document.pdf']
    );

    if ($result->hasSuccessfulUploads()) {
        echo "Uploaded " . $result->successfulCount . " files\n";
        foreach ($result->successfulFiles as $filePath) {
            echo "Saved: " . $filePath . "\n";
        }
    }
    
    if ($result->hasErrors()) {
        foreach ($result->getErrorMessages() as $errorMessage) {
            echo "Error: " . $errorMessage . "\n";
        }
    }
} catch (RuntimeException $e) {
    echo "Critical error: " . $e->getMessage() . "\n";
}

foreach ($result->successfulUploads as $upload) {
    echo $upload->originalFilename;
    echo $upload->requestedFilename;
    echo $upload->storedFilename;
    echo $upload->storedPath;
    echo $upload->mimeType;
    echo $upload->extension;
    echo $upload->sizeBytes;
    echo $upload->wasConverted ? 'converted' : 'original';
}

use FileUploadService\FileUploadService;
use FileUploadService\FilesystemSaver;

// Configure FilesystemSaver explicitly
$fileSaver = new FilesystemSaver('/var/www/uploads', 0755, true);
$service = new FileUploadService(['image', 'pdf'], $fileSaver);

$result = $service->save(
    input: $_FILES['files'],
    uploadDestination: 'photos',  // Relative to basePath
    filenames: ['photo1.jpg', 'photo2.jpg']
);

// Allow specific MIME types using 'mime:' prefix
$service = new FileUploadService([
    'image',                    // All image types
    'mime:text/csv',           // Custom CSV MIME type
    'mime:application/x-custom', // Custom application MIME type
    '.xyz'                     // Custom extension
]);

$service = new FileUploadService(['image']);

// Set allowed categories
$service->setAllowedCategories(['image', 'video']);

// Set custom extensions
$service->setAllowedExtensions(['xyz', 'custom']);

// Set custom MIME types
$service->setAllowedMimeTypes(['text/csv', 'application/x-custom']);

// Get current settings
$categories = $service->getAllowedCategories(); // Returns array<FileTypeEnum>
$extensions = $service->getAllowedExtensions(); // Returns array<string>
$mimeTypes = $service->getAllowedMimeTypes(); // Returns array<string>

$service = new FileUploadService([
    'image',                    // Image category
    'video',                    // Video category  
    'mime:text/csv',           // Custom CSV MIME type
    'mime:application/x-php',   // Custom PHP MIME type
    '.xyz',                    // Custom extension
    '.custom'                  // Another custom extension
]);

// Additional configuration via setters
$service->setAllowedMimeTypes(['text/plain', 'application/json']);
$service->setAllowedExtensions(['txt', 'json']);

// Allow video files
$service = new FileUploadService(['image', 'video']);

// Supported video formats:
// MP4, AVI, MOV, WMV, FLV, WebM, MKV, MPEG, MPG, 3GP, M4V, OGV

try {
    $result = $fileUploadService->save($input, $uploadDestination, $filenames);
    
    // Handle individual file results
    if ($result->hasSuccessfulUploads()) {
        // Process successful uploads
    }
    
    if ($result->hasErrors()) {
        // Handle individual file errors
    }
} catch (RuntimeException $e) {
    // Handle critical system errors
    error_log("File upload failed: " . $e->getMessage());
}

// Simple usage with raw strings (recommended)
$service = new FileUploadService([
    'image',
    'pdf',
    'video',
    'cad'
]);

// Allow all file types
$service = new FileUploadService(['all']);

// Mix categories, custom extensions, and MIME types
$service = new FileUploadService([
    'image',
    'video',
    'mime:text/csv',
    'mime:application/x-custom',
    '.xyz',
    '.custom'
]);

// Advanced usage with enums (optional)
use FileUploadService\Enum\FileTypeEnum;

$service = new FileUploadService([
    FileTypeEnum::IMAGE,
    FileTypeEnum::VIDEO,
    FileTypeEnum::PDF
]);

// Get all available file types - returns array of FileTypeEnum cases
$allFileTypes = FileUploadService::getAvailableFileTypeCategories();

// Enable HEIC to JPEG conversion (default)
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    convertHeicToJpg: true
);

// Disable HEIC conversion (save as-is)
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    convertHeicToJpg: false
);

// Check if HEIC conversion is available
if ($service->isHeicConversionEnabled()) {
    echo "HEIC conversion is enabled";
}

// Increment strategy (default): filename_1.jpg, filename_2.jpg
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    collisionStrategy: 'increment'
);

// UUID strategy: filename_a1b2c3d4.jpg
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    collisionStrategy: 'uuid'
);

// Timestamp strategy: filename_1234567890.jpg
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    collisionStrategy: 'timestamp'
);

// Advanced usage with enums (optional)
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    collisionStrategy: CollisionStrategyEnum::UUID
);

// Custom strategy
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    collisionStrategy: fn($base, $dir, $exts, $used) => $base . '_custom_' . bin2hex(random_bytes(4))
);

// Optimized for network storage or high-collision scenarios
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    highPerformanceMode: true
);
// Automatically uses 'uuid' strategy and filters extensions to reduce filesystem calls

// Enable rollback on error (default: false)
// When enabled, removes all successfully uploaded files if any error occurs
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    rollbackOnError: true
);

// Default behavior (rollback disabled)
$service = new FileUploadService(['image']); // rollbackOnError defaults to false

// Check if rollback is enabled
if ($service->isRollbackOnErrorEnabled()) {
    echo "Rollback is enabled";
}

use FileUploadService\FileUploadService;

// Simple approach: FilesystemSaver is auto-created from uploadDestination
$service = new FileUploadService(['image']);
$result = $service->save($_FILES['image'], '/var/www/uploads', ['photo.jpg']);
// Automatically creates FilesystemSaver with basePath derived from uploadDestination

// Advanced: Provide FilesystemSaver in constructor (backward compatible)
use FileUploadService\FilesystemSaver;
$filesystemSaver = new FilesystemSaver('/var/uploads', 0755, true);
$service = new FileUploadService(
    allowedFileTypes: ['image'],
    fileSaver: $filesystemSaver
);

// Advanced: Provide FileSaverInterface per save() call
$result = $service->save(
    input: $_FILES['image'],
    uploadDestination: 'uploads',
    filenames: ['photo.jpg'],
    fileSaver: $customFileSaver  // Optional override
);

// Cloud storage example (implement FileSaverInterface)
// $cloudSaver = new CloudStorageSaver('bucket-name', 'region', 'credentials');
// $service = new FileUploadService(['image']);
// $result = $service->save($input, 'uploads', $filenames, fileSaver: $cloudSaver);

$_FILES['files'] = [
    'name' => 'image.jpg',           // String
    'type' => 'image/jpeg',          // String  
    'tmp_name' => '/tmp/abc123',     // String
    'error' => 0,                    // Integer
    'size' => 12345                  // Integer
];

$_FILES['files'] = [
    'name' => ['image1.jpg', 'image2.png'],     // Array of strings
    'type' => ['image/jpeg', 'image/png'],      // Array of strings
    'tmp_name' => ['/tmp/abc123', '/tmp/def456'], // Array of strings
    'error' => [0, 0],                          // Array of integers
    'size' => [12345, 67890]                    // Array of integers
];

$dataUri = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...';

$input = [
    'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...',  // base64
    $_FILES['uploaded_file'],                                // $_FILES
    'data:application/pdf;base64,JVBERi0xLjQKMSAwIG9i...', // base64
    $_FILES['another_file']                                  // $_FILES
];
$filenames = ['image1.jpg', 'upload1.pdf', 'document.pdf', 'file2.doc'];
$result = $fileUploadService->save($input, $uploadDestination, $filenames);

public function __construct(
    private readonly array $allowedFileTypes = [FileTypeEnum::IMAGE, FileTypeEnum::PDF, FileTypeEnum::CAD],
    private readonly ?FileSaverInterface $fileSaver = null,
    private readonly bool $createDirectory = true,
    private readonly int $directoryPermissions = 0775,
    private readonly bool $rollbackOnError = false,
    string|callable|CollisionStrategyEnum $collisionStrategy = CollisionStrategyEnum::INCREMENT,
    private readonly bool $highPerformanceMode = false,
    private readonly bool $convertHeicToJpg = true
)