zdenekgebauer / upload
Upload handler
2.1.0
2026-11-30 12:06 UTC
Requires
- php: >=8.4
- ext-fileinfo: *
- psr/http-message: ^2.0
Requires (Dev)
- codeception/codeception: ^5.3
- codeception/module-asserts: ^3.3
- guzzlehttp/psr7: ^3.6
- infection/codeception-adapter: ^0.4
- infection/infection: ^0.35
- phpstan/phpstan: ^2.3
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-strict-rules: ^2.1
- rector/rector: ^2.9
- symplify/easy-coding-standard: ^13.3
Suggests
None
Provides
None
Conflicts
None
Replaces
None
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-fileinfopsr/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:
| Case | Value | Meaning |
|---|---|---|
UploadError::FILE_ALREADY_EXISTS | 1000 | File exists and overwrite is disabled |
UploadError::FORBIDDEN_EXTENSION | 1001 | Extension not in the allowed list |
UploadError::FORBIDDEN_MIME | 1002 | MIME type not allowed, or unrecognised image format |
UploadError::INCORRECT_IMAGE_SIZE | 1003 | Image dimensions outside the configured constraints |
UploadError::FILE_TOO_LARGE | 1004 | File exceeds maxFileSize |
UploadError::CHMOD_FAILED | 1005 | File was saved, but its permissions could not be set |
UploadError::MISSING_FILE_NAME | 1006 | Target 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.PDFnow passessetAllowedExtensions(['pdf']). - A client filename is reduced to its basename when the target is a directory, so
sub/photo.jpgis saved asphoto.jpgdirectly in the target directory. save()throwsUploadError::MISSING_FILE_NAMEwhen the target is a directory and the client sent no filename, andUploadError::CHMOD_FAILEDwhen the permissions cannot be set.- The error code constants on
UploadExceptionare deprecated — useUploadErrorinstead.
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.