PHP code example of phatnt93 / php-upload-helper

1. Go to this page and download the library: Download phatnt93/php-upload-helper 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/ */

    

phatnt93 / php-upload-helper example snippets


use UploadHelper\Upload;

// Process a single file from $_FILES['avatar']
$result = Upload::file($_FILES['avatar'])
    ->allowedExtensions(['jpg', 'jpeg', 'png', 'webp'])
    ->maxSize('5M')
    ->slugName()
    ->resize(400, 400, mode: 'crop')
    ->toWebp(quality: 85)
    ->saveTo('/var/www/uploads/avatars');

if ($result->isSuccess()) {
    echo "Saved to: " . $result->getFilePath();
    echo "Filename: " . $result->getFilename();
    echo "File size: " . $result->getFormattedSize();
} else {
    echo "Upload failed: " . $result->getErrorMessage();
}

use UploadHelper\Upload;

// Feed the raw $_FILES array directly:
$batch = Upload::files($_FILES['photos'])
    ->allowedExtensions(['jpg', 'png', 'webp'])
    ->maxSize('10M')
    ->each(function ($builder, $index) {
        $builder->randomName(16)
                ->resize(1200, 800, mode: 'fit')
                ->watermarkImage('/path/to/watermark.png', position: 'bottom-right', opacity: 70)
                ->saveTo('/var/www/uploads/gallery');
    })
    ->rollbackOnError(true) // Automatically deletes saved files if any file in the batch fails
    ->process();

if ($batch->allSuccessful()) {
    echo "All " . count($batch->getSuccessful()) . " files uploaded successfully!";
    foreach ($batch->getSuccessful() as $file) {
        echo "- " . $file->getFilename() . " (" . $file->getFormattedSize() . ")\n";
    }
} else {
    echo "Batch failed with " . count($batch->getFailed()) . " error(s):\n";
    foreach ($batch->getFailed() as $failed) {
        echo "- " . $failed->getOriginalName() . ": " . $failed->getErrorMessage() . "\n";
    }
}

use UploadHelper\Upload;

// Automatically flattens and normalizes any nested upload array:
$batch = Upload::files($_FILES['catalog'])
    ->allowedExtensions(['pdf', 'docx', 'jpg', 'png'])
    ->maxSize('20M')
    ->saveTo('/var/www/uploads/catalog')
    ->process();

foreach ($batch->getSuccessful() as $processed) {
    echo "Field: " . $processed->getFieldKey() . "\n";
    echo "Original: " . $processed->getOriginalName() . " -> Saved: " . $processed->getFilename() . "\n";
}

use UploadHelper\Upload;

$result = Upload::file($_FILES['avatar'])
    ->allowedExtensions(['jpg', 'jpeg', 'png', 'webp'])
    ->allowedMimes(['image/jpeg', 'image/png', 'image/webp'])
    ->maxSize('2M')
    ->dimensionBetween(minW: 100, minH: 100, maxW: 4000, maxH: 4000)
    ->autoOrient()                                // Fix orientation for mobile camera selfies
    ->resize(300, 300, mode: 'crop')             // Smart center crop
    ->toWebp(quality: 85)                        // High-efficiency WebP compression
    ->name('user_' . $userId . '_avatar')
    ->overwrite(true)                            // Update existing avatar
    ->saveTo('/var/www/app/public/uploads/avatars');

if ($result->isSuccess()) {
    $avatarUrl = '/uploads/avatars/' . $result->getFilename();
    // Update database with $avatarUrl
}

use UploadHelper\Upload;

$batch = Upload::files($_FILES['product_images'])
    ->allowedExtensions(['jpg', 'jpeg', 'png'])
    ->maxSize('8M')
    ->each(function ($builder, $i) use ($productId) {
        $builder->name("product_{$productId}_img_" . ($i + 1))
                ->resize(1200, 1200, mode: 'fit')
                ->watermarkImage(
                    watermarkPath: '/assets/img/watermark-logo.png',
                    position: 'bottom-right',
                    opacity: 75,
                    offsetX: 20,
                    offsetY: 20
                )
                ->toJpeg(quality: 88)
                ->saveTo("/var/www/app/storage/products/{$productId}");
    })
    ->rollbackOnError(true) // Crucial: clean disk if any file exceeds size or is corrupt
    ->process();

if ($batch->allSuccessful()) {
    foreach ($batch->getSuccessful() as $item) {
        $db->insertProductImage($productId, $item->getFilename());
    }
} else {
    // Zero disk pollution: all previously saved files were deleted automatically!
    $errors = $batch->getErrors();
    $_SESSION['flash_error'] = "Upload failed: " . implode(', ', array_column($errors, 'message'));
}

use UploadHelper\Upload;

$result = Upload::file($_FILES['resume'])
    ->allowedExtensions(['pdf', 'docx', 'doc'])
    ->allowedMimes([
        'application/pdf',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword',
    ])
    ->maxSize('15M')
    ->slugName() // "Báo cáo tài chính quý 3.pdf" -> "bao-cao-tai-chinh-quy-3.pdf"
    ->autoIncrementDuplicate(true) // If exists: "bao-cao-tai-chinh-quy-3_1.pdf"
    ->saveTo('/var/www/app/storage/documents', chmod: 0750);

if ($result->isSuccess()) {
    echo "Saved safely at: " . $result->getFilePath();
}

use UploadHelper\Upload;

$result = Upload::file($_FILES['company_logo'])
    ->allowedExtensions(['svg'])
    ->allowedMimes(['image/svg+xml'])
    ->maxSize('1M')
    ->sanitizeSvg(true) // Strips <script>, <foreignObject>, onload, onerror, javascript:
    ->uuidName()        // Generates UUID v4 name
    ->saveTo('/var/www/app/public/logos');

if ($result->isSuccess()) {
    echo "Clean, XSS-free SVG saved: " . $result->getFilename();
}

use UploadHelper\Upload;

// 1. Mobile / Web Canvas Base64 Data URI:
$base64String = $requestPayload['avatar_base64']; // "data:image/png;base64,iVBORw0KGgo..."
$result = Upload::fromBase64($base64String, filename: 'canvas_drawing.png')
    ->maxSize('3M')
    ->resize(500, 500, mode: 'fit')
    ->toWebp(quality: 80)
    ->saveTo('/uploads/drawings');

// 2. PSR-7 UploadedFile (Slim, Laminas, Nyholm, Guzzle):
$psr7File = $request->getUploadedFiles()['profile_picture'];
$result = Upload::fromPsr7($psr7File)
    ->allowedExtensions(['jpg', 'png'])
    ->saveTo('/uploads/profiles');

// 3. Download from Remote URL:
$result = Upload::fromUrl('https://images.unsplash.com/photo-1579783900882-c0d3dad7b119')
    ->resize(800, 600)
    ->saveTo('/uploads/unsplash');

// Standard Web Form Input
$builder = Upload::file($_FILES['avatar']);             // Single $_FILES element
$batch   = Upload::files($_FILES['photos']);            // Multi-file $_FILES element
$batch   = Upload::fromGlobals();                       // All $_FILES at once

// Alternative Sources
$builder = Upload::fromPath('/path/to/local/file.jpg');
$builder = Upload::fromBase64('data:image/png;base64,iVBORw0KGgo...', 'avatar.png');
$builder = Upload::fromUrl('https://example.com/asset.png', timeout: 15, maxDownloadBytes: 52_428_800);
$builder = Upload::fromPsr7($psr7UploadedFile);

$builder->resize(800, 600, mode: 'fit', background: '#FFFFFF');

$builder->crop(400, 300, x: 10, y: 10);                           // Freeform rectangle
$builder->rotate(90.0, background: '#000000');                    // Custom angle rotation
$builder->flipHorizontal();                                      // Horizontal mirror
$builder->flipVertical();                                        // Vertical mirror
$builder->autoOrient();                                          // Read EXIF camera orientation
$builder->stripExif(keepOrientation: true);                     // Strip GPS and camera metadata for user privacy

// Image Overlay:
$builder->watermarkImage(
    watermarkPath: '/path/to/watermark.png',
    position: 'bottom-right', // 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'center'
    opacity: 80,              // 0 to 100%
    offsetX: 15,
    offsetY: 15,
);

// TrueType Text Watermark:
$builder->watermarkText(
    text: '© 2026 MyBrand',
    fontPath: '/path/to/font.ttf',   // Path to .ttf font file (uses built-in font if omitted)
    size: 16,
    color: '#FFFFFF',                // Hex color
    position: 'bottom-right',
    background: '#000000',           // Optional background padding block
    backgroundOpacity: 50,
    offsetX: 10,
    offsetY: 10,
);

$builder->grayscale();       // Convert to black and white
$builder->brightness(20);    // Brightness: -255 to +255
$builder->contrast(-10);     // Contrast: -100 to +100
$builder->blur();            // Gaussian blur
$builder->sharpen();         // Unsharp mask filter
$builder->invert();          // Invert image colors

$result = Upload::file($_FILES['photo'])->saveTo('/uploads');

if ($result->isSuccess()) {
    $file = $result->getFile(); // Instance of ProcessedFile
    
    echo $file->getOriginalName();      // e.g. "My Picture.png"
    echo $file->getFilename();          // e.g. "my-picture.webp"
    echo $file->getSavedPath();         // e.g. "/uploads/my-picture.webp"
    echo $file->getFilePath();          // Alias to getSavedPath()
    echo $file->getMime();              // e.g. "image/webp"
    echo $file->getExtension();          // e.g. "webp"
    echo $file->getSize();              // Size in bytes
    echo $file->getFormattedSize();     // e.g. "1.42 MB"
    echo $file->getWidth();             // e.g. 1200
    echo $file->getHeight();            // e.g. 800
    print_r($file->getDimensions());    // ['width' => 1200, 'height' => 800]
    print_r($file->toArray());          // Export array
} else {
    echo $result->getErrorMessage();    // Translated error message
    echo $result->getErrorCode();       // e.g. "ERR_FILE_TOO_LARGE"
    print_r($result->getErrors());      // ['code' => ..., 'message' => ..., 'context' => ...]

    // Technical detail for logs only (English, may contain paths) - never show it to end users:
    error_log($result->getErrors()['context']['reason'] ?? '');
}

$batch = Upload::files($_FILES['photos'])
    ->saveTo('/uploads/gallery')
    ->rollbackOnError(true)
    ->process();

$batch->allSuccessful();    // Returns true if all files succeeded
$batch->hasFailures();      // Returns true if one or more files failed
$batch->count();            // Total processed files count

// Access lists:
$batch->getSuccessful();    // Array of ProcessedFile objects
$batch->getFailed();        // Array of SingleResult error objects
$batch->getErrors();        // Array of error details keyed by original name

use UploadHelper\Upload;

$result = Upload::file($_FILES['avatar'])
    ->allowedExtensions(['jpg', 'jpeg', 'png', 'webp'])
    ->slugName()
    ->destination('/var/www/uploads/avatars/original') // Main/Original file destination
    // Variant 1: Square thumbnail for profile lists
    ->variant('thumb', function ($v) {
        $v->resize(150, 150, mode: 'crop')
          ->toWebp(quality: 80)
          ->saveTo('/var/www/uploads/avatars/thumbs');
    })
    // Variant 2: Mid-size preview for profile header
    ->variant('preview', function ($v) {
        $v->resize(600, 400, mode: 'fit')
          ->toWebp(quality: 85)
          ->saveTo('/var/www/uploads/avatars/previews');
    })
    ->process();

if ($result->isSuccess()) {
    echo "Original: " . $result->getFilePath() . "\n";
    
    // Access variants easily:
    $thumb = $result->getVariant('thumb');
    echo "Thumbnail: " . $thumb->getSavedPath() . " (" . $thumb->getWidth() . "x" . $thumb->getHeight() . ")\n";
    
    $preview = $result->getVariant('preview');
    echo "Preview: " . $preview->getSavedPath() . "\n";
    
    // Access all variants:
    foreach ($result->getVariants() as $name => $variantFile) {
        echo "- Variant '{$name}': " . $variantFile->getFilename() . "\n";
    }
}

Upload::file($_FILES['contract'])
    ->beforeProcess(function (UploadedFile $uploadedFile): void {
        // Runs before validation & processing
        Log::info("Starting upload for: " . $uploadedFile->getOriginalName());
    })
    ->onSuccess(function (ProcessedFile $processedFile, SingleResult $result): void {
        // Runs only when upload succeeded
        Database::recordUpload($processedFile->getFilename(), $processedFile->getSize());
        Notification::send("Upload complete!");
    })
    ->onError(function (string $errorMessage, string $errorCode, SingleResult $result): void {
        // Runs when validation or processing failed
        Log::warning("Upload failed [{$errorCode}]: {$errorMessage}");
    })
    ->afterProcess(function (SingleResult $result): void {
        // Always runs after process finishes (success or failure)
        Metrics::increment('uploads.attempted');
    })
    ->saveTo('/uploads/contracts');

// upload.php
lper\Upload;

$batch = Upload::files($_FILES['photos'])
    ->allowedExtensions(['jpg', 'png', 'webp'])
    ->maxSize('5M')
    ->slugName()
    ->resize(1200, 800)
    ->toWebp(85)
    ->saveTo(__DIR__ . '/public/uploads')
    ->rollbackOnError(true)
    ->process();

if ($batch->allSuccessful()) {
    header('Location: /gallery.php?success=1');
} else {
    echo "Errors: " . json_encode($batch->getErrors());
}

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use UploadHelper\Upload;

class MediaController extends Controller
{
    public function uploadAvatar(Request $request)
    {
        $request->validate(['avatar' => 'tensions(['jpg', 'jpeg', 'png', 'webp'])
            ->maxSize('5M')
            ->resize(400, 400, mode: 'crop')
            ->toWebp()
            ->saveTo(public_path('uploads/avatars'));

        if (!$result->isSuccess()) {
            return back()->withErrors(['avatar' => $result->getErrorMessage()]);
        }

        auth()->user()->update(['avatar' => $result->getFilename()]);
        return back()->with('status', 'Avatar updated!');
    }
}

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use UploadHelper\Upload;

class UploadController extends AbstractController
{
    public function handleUpload(Request $request): Response
    {
        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile */
        $uploadedFile = $request->files->get('document');

        $result = Upload::fromPath($uploadedFile->getRealPath(), $uploadedFile->getClientOriginalName())
            ->allowedExtensions(['pdf', 'docx'])
            ->maxSize('10M')
            ->slugName()
            ->saveTo($this->getParameter('kernel.project_dir') . '/var/uploads');

        if ($result->isSuccess()) {
            return $this->json(['status' => 'success', 'filename' => $result->getFilename()]);
        }

        return $this->json(['error' => $result->getErrorMessage()], 422);
    }
}

namespace App\Controllers;

use Phalcon\Mvc\Controller;
use UploadHelper\Upload;

class FileController extends Controller
{
    public function uploadAction()
    {
        if ($this->request->hasFiles()) {
            $batch = Upload::fromGlobals($_FILES)
                ->allowedExtensions(['jpg', 'png', 'webp'])
                ->maxSize('8M')
                ->saveTo($this->config->application->uploadDir)
                ->process();

            if ($batch->allSuccessful()) {
                $this->flash->success("Uploaded " . count($batch->getSuccessful()) . " files!");
            } else {
                $this->flash->error("Failed to upload some files.");
            }
        }
    }
}

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use UploadHelper\Upload;

$app->post('/api/upload', function (Request $request, Response $response) {
    $uploadedFiles = $request->getUploadedFiles();
    $avatar = $uploadedFiles['avatar'] ?? null;

    if (!$avatar) {
        $response->getBody()->write(json_encode(['error' => 'No file uploaded']));
        return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
    }

    $result = Upload::fromPsr7($avatar)
        ->allowedExtensions(['jpg', 'png', 'webp'])
        ->maxSize('2M')
        ->resize(300, 300, mode: 'crop')
        ->toWebp()
        ->saveTo(__DIR__ . '/public/uploads');

    $response->getBody()->write(json_encode([
        'success'  => $result->isSuccess(),
        'filename' => $result->getFilename(),
        'error'    => $result->getErrorMessage(),
    ]));
    
    return $response->withHeader('Content-Type', 'application/json');
});

use UploadHelper\I18n\Translator;

// Switch the locale globally (format: "xx", "xxx" or "xx_YY"; anything else throws InvalidLocaleException):
Translator::setLocale('vi');

// Register or override translations for any locale:
Translator::addTranslations('es', [
    'ERR_FILE_TOO_LARGE'        => 'El archivo ({formatted_actual}) supera el máximo permitido ({formatted_max}).',
    'ERR_EXTENSION_NOT_ALLOWED' => 'La extensión .{extension} no está permitida.',
]);
Translator::setLocale('es');

Translator::has('ERR_FILE_TOO_LARGE', 'es'); // true

$result = Upload::file($_FILES['photo'])
    ->allowedExtensions(['jpg', 'png', 'webp'])
    ->resize(800, 600, mode: 'contain')
    ->prefix('preview_')
    ->variant('thumb', function ($v): void {
        $v->resize(150, 150, mode: 'cover')
            ->prefix('thumb_')
            ->toWebp(quality: 80);
    })
    ->saveTo('/uploads/gallery');
bash
composer 
ini
file_uploads = On
upload_max_filesize = 50M
post_max_size = 60M
max_file_uploads = 50
memory_limit = 256M
bash
php -r "var_dump(function_exists('imagewebp'));"
php -r "var_dump(function_exists('imageavif'));"