Search by

Upload handler

Package info

gitlab.com/zdenekgebauer/upload

pkg:composer/zdenekgebauer/upload

Statistics

Installs: 8

Dependents: 0

Suggesters: 0

Stars: 0

2.1.0 2026-11-30 12:06 UTC

This package is auto-updated.

Last update: 2026-11-30 11:10:18 UTC


README

Handle uploaded files

Features

  • upload single or multiple files
  • validates file extension and MIME type (both case-insensitive) and file size on the server side
  • validates image dimensions (exact size or maximum size)
  • expects PSR-7 compatible UploadedFileInterface
  • a client supplied filename is reduced to its basename, so it cannot escape the target directory

Requirements

  • PHP 8.4+
  • ext-fileinfo
  • psr/http-message ^2.0

Installation

composer require zdenekgebauer/upload

Usage

Single file

$request = GuzzleHttp\Psr7\ServerRequest::fromGlobals();

$uploader = new \ZdenekGebauer\Upload\Uploader();

$uploadOptions = new \ZdenekGebauer\Upload\UploadOptions();
// overwrite existing file (default: true)
$uploadOptions->setOverwriteFile(false);
// set file permissions (default: 0644)
$uploadOptions->setFilePermissions(0o644);
// allow only specified extensions — matching is case-insensitive ('JPG' matches 'jpg')
$uploadOptions->setAllowedExtensions(['png', 'jpg', 'jpeg', 'gif']);
// allow only specified MIME types — matching is case-insensitive
// (detected server-side via finfo on the file the stream points to, the client value is ignored)
$uploadOptions->setAllowedMimeTypes(['image/png', 'image/jpeg', 'image/gif']);
// max image dimensions — 0 means "no restriction on that axis"
$uploadOptions->setMaxImageSize(1000, 800);
// or require an exact size
$uploadOptions->setRequiredImageSize(640, 480);
// max file size in bytes — 0 means no restriction
$uploadOptions->setMaxFileSize(5 * 1024 * 1024);

try {
    // save to directory — uses the original client filename
    $uploader->save($request->getUploadedFiles()['file'], 'some/dir', $uploadOptions);
    // or save to an explicit path
    $uploader->save($request->getUploadedFiles()['file'], 'some/dir/custom-filename.jpg', $uploadOptions);
} catch (\ZdenekGebauer\Upload\UploadException $e) {
    echo $e->getMessage(), ' (code ', $e->getCode(), ')';
}

Multiple files

$uploader = new \ZdenekGebauer\Upload\Uploader();

try {
    $uploader->saveAll($request->getUploadedFiles(), 'some/dir');
} catch (\ZdenekGebauer\Upload\UploadException $e) {
    echo $e->getMessage(), ' (code ', $e->getCode(), ')';
}

Error codes

Error codes are defined in \ZdenekGebauer\Upload\UploadError:

CaseValueMeaning
UploadError::FILE_ALREADY_EXISTS1000File exists and overwrite is disabled
UploadError::FORBIDDEN_EXTENSION1001Extension not in the allowed list
UploadError::FORBIDDEN_MIME1002MIME type not allowed, or unrecognised image format
UploadError::INCORRECT_IMAGE_SIZE1003Image dimensions outside the configured constraints
UploadError::FILE_TOO_LARGE1004File exceeds maxFileSize
UploadError::CHMOD_FAILED1005File was saved, but its permissions could not be set
UploadError::MISSING_FILE_NAME1006Target is a directory and the client sent no usable filename

When the upload itself failed, the exception code is the PHP UPLOAD_ERR_* constant and the message is the matching description.

The constants with the same names on UploadException are deprecated aliases kept for backwards compatibility — use UploadError in new code.

try {
    $uploader->save($uploadedFile, 'some/dir', $uploadOptions);
} catch (\ZdenekGebauer\Upload\UploadException $e) {
    match ($e->getCode()) {
        \ZdenekGebauer\Upload\UploadError::FORBIDDEN_EXTENSION->value => 'wrong extension',
        \ZdenekGebauer\Upload\UploadError::FORBIDDEN_MIME->value      => 'wrong MIME type',
        default                                                        => 'other error',
    };
}

Dependency injection

Type-hint against UploaderInterface to keep consuming code testable:

use ZdenekGebauer\Upload\UploaderInterface;

class MyService
{
    public function __construct(private readonly UploaderInterface $uploader) {}
}

Upgrading from 1.x

See CHANGELOG.md for the full list. The changes most likely to need attention:

  • PHP 8.4 or newer is required.
  • Extensions and MIME types are matched case-insensitively — photo.PDF now passes setAllowedExtensions(['pdf']).
  • A client filename is reduced to its basename when the target is a directory, so sub/photo.jpg is saved as photo.jpg directly in the target directory.
  • save() throws UploadError::MISSING_FILE_NAME when the target is a directory and the client sent no filename, and UploadError::CHMOD_FAILED when the permissions cannot be set.
  • The error code constants on UploadException are deprecated — use UploadError instead.

Development

Local environment runs on Lando (Docker, PHP 8.5 + xdebug):

lando start          # start the environment
lando install        # install dependencies
lando tests          # run the test suite
lando coverage       # test suite with code coverage
lando ecs            # coding standards (lando ecs-fix to apply)
lando infection      # mutation testing, requires 100 % MSI
lando phpstan        # static analysis, level max
lando rector         # modernization dry-run (lando rector-fix to apply)

License

MIT — see LICENSE.